//收银首页控制器
var CashierIndexCtrl = ['$scope', '$rootScope', '$location', '$interval', '$timeout', 'ShopGetFriend', 'BaseGoods', 'GoodsCart', 'VIP', 'Coupon', 'UserLoginCheck', 'ReceiptRecord', 'ngDialog', 'ShopSetCheck', 'Promotion', 'timeStamp2String', 'Cards', 'PosUser', 'LackRegister', 'ServiceOrder', 'ShopAttend', 'apiService', 'ThirdDev',
    function ($scope, $rootScope, $location, $interval, $timeout,
            ShopGetFriend, BaseGoods, GoodsCart, VIP, Coupon,
            UserLoginCheck, ReceiptRecord, ngDialog, ShopSetCheck, Promotion,
            timeStamp2String, Cards, PosUser, LackRegister,
            ServiceOrder, ShopAttend, apiService, ThirdDev) {

        ShopSetCheck(); //检查店铺是否绑定
        $scope.is_lqx = ThirdDev.is_lqx();
        var configData = $api.getStorage('configData');
        $rootScope.cashNum = configData.cashsetData.cashNum;
        $rootScope.cashDate = configData.cashsetData.cashDate;
        $scope.checkNum = configData.standard_coin;
        //
        if ($rootScope.purview['\/MainCtrl\/cashDeskSet'].show == 1) {
            if (configData.finished == '1') {
                $location.path('/index');
                return;
            }
        }
        //属性 ===============================================================
        $scope.input_keyword = ''; //界面主输入框的内容
        $scope.suk_num_max = 50; //查询商品最大显示的条目
        $scope.input_keyword_inv = ''; //库存查询弹出框的输入内容
        $scope.input_tips = {
            'sku': $rootScope.language.MSG_INPUT_SKU, //请输入商品编号
            'vip': $rootScope.language.MSG_INPUT_VIP_NUM, //请输入会员手机号
            'num': $rootScope.language.MSG_INPUT_MODIFY_NUM, //请输入要修改的数量
            'price': $rootScope.language.MSG_INPUT_MODIFY_PRICE, //请输入要修改的价格
            'rebate': $rootScope.language.MSG_INPUT_MODIFY_DISCOUNT, //请输入要修改的折扣
            'money': $rootScope.language.MSG_INPUT_MODIFY_MONEY, //请输入要修改的金额
            'coupon': $rootScope.language.MSG_INPUT_COUPON, //请输入优惠券号
            'keyboardOpen': $rootScope.language.MSG_KEYBOARD_OPEN, //系统键盘已打开
            'keyboardClose': $rootScope.language.MSG_KEYBOARD_CLOSE//系统键盘已关闭

        };
        $scope.selector = 'vip'; //输入框输入状态：选商品/选会员/改商品数量
        $scope.selector_class = ''; //商品输入按钮切换状态：默认空为VIP，sku为输入商品

        switch (configData.default_input) {
            case '0':
            case 0:
                $scope.selector = 'vip'; //输入框输入状态：选商品/选会员/改商品数量
                $scope.selector_class = '';
                break;
            case '1':
            case 1:
                $scope.selector = 'sku'; //输入框输入状态：选商品/选会员/改商品数量
                $scope.selector_class = 'sku';
                break;
            case '2':
            case 2:
                $scope.selector = 'coupon'; //输入框输入状态：选商品/选会员/改商品数量
                break;
            default:
                $scope.selector = 'sku'; //输入框输入状态：选商品/选会员/改商品数量
        }

        $rootScope.saveMoneyByPrice = []; //通过修改价格折扣金额的价格变化
        $scope.goods_select_data = []; //商品选择器弹框的数据
        $scope.goods_select_data_choose = 0; //商品选择器弹框当前选中的数组项的index
        $scope.vip_select_data = []; //会员选择器弹框的数据
        $scope.get_receipt_data = {}; //读取的挂单的数据
        $scope.get_receipt_data_remark = {}; //读取的挂单的备注数据
        $scope.get_receipt_index = 0; //读取的挂单的数据
        $scope.isChangeSpecifications = false;//标示是否在进行修改商品规格
        var window_id = 0; //弹框ID标识
        var enquiry = 0;
        var window_cur = 0;
        $rootScope.zk = ''; //全局变量  外卡折扣
        $rootScope.yxdjsy = ''; //全局变量  是否允许外卡和会员卡同时使用
        $scope.animate_class = {}; //按键动画状态数据  animate_class[7] = 'click' 表示7键被按下
        $scope.add_customer_enable = true; //保存顾客开关，避免多次重复提交 true可以点击，false不可以点击
        //底部更多按钮开关
        $scope.more_btns_active = '';
        $scope.more_btns_toggle = function () {
            if ($scope.more_btns_active == '') {
                $scope.more_btns_active = 'active';
            } else {
                $scope.more_btns_active = ''
            }
            return false;
        };
        //会员信息栏滑动
        $scope.member_li = {
            current: 0,
            max: 1
        };
        $scope.tabs = function (arr) {
            if (arr == 'next') {
                $scope.member_li.current++;
            } else if (arr == 'last') {
                $scope.member_li.current--;
            }
            if ($scope.member_li.current > $scope.member_li.max) {
                $scope.member_li.current = 0;
            }
            if ($scope.member_li.current < 0) {
                $scope.member_li.current = $scope.member_li.max;
            }
        };
        $scope.jump = function (n) {
            $scope.member_li.current = n;
        }
        //购物车导购员列表
        //$scope.selectedGuide = []; 
        $scope.memberGuide = [];
        //判断导购类型
        $scope.configData = $api.getStorage('configData');
        //初始化挂单数组
        if (typeof $rootScope.hold_receipt_data == 'undefined') {
            $rootScope.hold_receipt_data = [];
        }
        $scope.endCash = function () {
            //判断是否结束营业
            if ($rootScope.purview['\/CashierIndexCtrl\/end_sale'].show == 0) {
                return;
            }
            //判断是否有日结的权限
            if ($rootScope.purview['\/Cunhuo\/finished_sale'].show == 0) {
                return;
            }

            finiash_cashier = ngDialog.open({closeByDocument: false,
                template: './html/component/confirm.html',
                disableAnimation: true,
                trapFocus: false,
                scope: $scope,
                preCloseCallback: function () {
                    $scope.open_windows.pop();
                },
                controller: [function () {
                        //标题
                        $scope.title = $rootScope.language.TIP_CASHIER_TITLE;
                        //内容
                        $scope.info = $rootScope.language.TIP_INDEX_GOTO_FINISHED_COMFIRM;
                    }]
            });
            $scope.open_windows.push('nothing');
            //确认
            $scope.confirm = function () {
//                $rootScope.hold_receipt_data.splice(index, 1);
                var configData = $api.getStorage('configData');
                configData.finished = 1;
                $api.setStorage('configData', configData);
                //结束营业的时候 清空购物车
                GoodsCart.clear_cart();
                baison_app.api.toast({msg: $rootScope.language.TIP_INDEX_FINISHED_COMFIRM}); //结束营业
                ngDialog.close(finiash_cashier);
                //上传营业状态到服务器
                $scope.cashDate = new Date();
                var nowTime = timeStamp2String($scope.cashDate, 'datetime');
                var param = {
                    cashier_time: configData.cashierTime,
                    operate_time: nowTime
                };
                ShopAttend.shop_status(param, 0);
                $scope.open_windows.pop();
                $location.path('/finished/index');
            };

            //取消
            $scope.cancel = function () {
                $scope.open_windows.pop();
                ngDialog.close(finiash_cashier);
            }
            ;
        };
        //当前打开的窗口栈，最新打开的最后关闭
        //用于控制在不同的窗口下，方向快捷键处理的数据不同，默认初始窗口名为'main'
        //示例： ['main','goods_selector','vip_selector']
        $scope.open_windows = ['main'];
        //登录判断
        UserLoginCheck();
        //购物车列表
        if (!$rootScope.goods_cart) {
            GoodsCart.init();
        }

//获取当前导购员列表
        PosUser.get_list_all({'UserStatus': 1, 'ShopCode': $rootScope.current_shop.ShopCode}).then(function (ret) {
            $scope.memberGuide = ret;
            $rootScope.goods_cart.guidelist = ret;
            $scope.memberManager = [];
            ret.forEach(function (n) {
                if (n.role_id == "13") {
                    $scope.memberManager.push(n);
                }
            });
        });
        //GoodsCart.get_available_promotion();
        $scope.rebate_open = true;
        $scope.sku_price = true;
        var configData = $api.getStorage('configData');
        //lqx 标准价

        if ($rootScope.purview['\/CashierIndexCtrl\/hide_price'].show == 0) {
            $scope.rebate_open = false;
            $scope.sku_price = false;
        }
//        if (GetCustomerInfo('type') == 1) { //lqx 标准价格不显示 
//            $scope.rebate_open = false;
//            $scope.sku_price = false;
//        }
        //促销赠件，获取赠件物品
        var get_promotion_gift_goods = function () {
            Promotion.get_available_promotion().then(function (success) {
                $.each($rootScope.goods_cart.available_promotions, function (i, n) {
                    if (Promotion.check_current_prom(n.promotion_rule_id, $rootScope.goods_cart.current_promotions)) {
                        //console.log(JSON.stringify(n));
                        if (n.promotion_type == 1 || n.promotion_type == 3) {
                            get_gift_goods(n);
                        }
                    }
                });
            });


        };
        //私有方法 ==============================================================//
        //根据页面输入查询商品
        var search_goods = function (codeStr) {
//      	var start = new Date().getTime();//起始时间
//      	var end = '';
//      	var time = '';
//      	for(var i = 0;i< 50;i++){
            //判断是否有搜索商品的权限
            if ($rootScope.purview['\/unset3'].show == 0) {
				baison_app.api.toast({msg: $rootScope.language.TIPS_NO_POWER}); //没有找到商品
                return;
            }
            BaseGoods.get_sku_by_code(codeStr).then(function (sku) {

//	                end = new Date().getTime();//起始时间
//	                time= (end - start)+"ms";//返回函数执行需要时间
//					if(i == 49){
//						baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON],msg:parseFloat(time/50),title:'查询时间'});
//					}
                if (sku.length == 0) {
                    baison_app.api.toast({msg: $rootScope.language.MSG_NOT_FOUND_GOODS}); //没有找到商品
                } else if (sku.length == 1) {
                    //判断库存是否小于0，若小于0，显示红色
                    if (sku[0].SkuNum <= 0) {
                        sku[0].flag = 1;
                        $scope.input_keyword = '';
                        $scope.selector = 'sku';
                        $scope.selector_class = 'sku';
                    }
                    if ($rootScope.user.UserCode == '000') {
                        if (typeof $scope.memberGuide != 'undefined' && $scope.memberGuide.length != 0) {
                            GoodsCart.add_to_cart(sku[0], $scope.configData.daogou, $scope.memberGuide[0].UserCode);
                        } else {
                            GoodsCart.add_to_cart(sku[0], $scope.configData.daogou, "000");
                        }
                    } else {
                        GoodsCart.add_to_cart(sku[0], $scope.configData.daogou, $rootScope.user.UserCode);
                    }
                    //TODO ??????????????

                    //get_promotion_gift_goods();


                } else if (sku.length <= $scope.suk_num_max) {
                    $scope.goods_select_data = sku;
                    $scope.goods_select_data_choose = 0;
                    window_id = ngDialog.open({closeByDocument: false,
                        trapFocus: false,
                        template: './html/component/goods_select.html',
                        disableAnimation: true,
                        scope: $scope,
                        preCloseCallback: function () {
                            $scope.open_windows.pop();
                        }
                    });
                    $scope.open_windows.push('goods_selector');
                } else {
                    baison_app.api.toast({msg: $rootScope.language.MSG_GOODS_MORE_INPUT_CODE}); //查到的商品太多，请输入更完整的条码
                }
            }, function (err) {
                baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: err});
            });
            //}
        };
        //离线会员销售逻辑
        var offline_vip_window = '';
        var offline_vip_logic = function (vip_tel) {
            //弹出确认
            baison_app.api.confirm({
                title: $rootScope.language.TIP_CASHIER_TITLE,
                msg: $rootScope.language.TIP_CASHIER_MESSAGE,
                buttons: [$rootScope.language.COMMON_CONFIRM, $rootScope.language.ACT_CANCEL]
            }, function (ret, err) {
                if (ret.buttonIndex == 1) {
                    //弹出录入会员信息页面
                    offline_vip_window = ngDialog.open({closeByDocument: false,
                        trapFocus: false,
                        template: './html/cashier/dialog/offline_vip_cashier.html',
                        disableAnimation: true,
                        scope: $scope,
                        controller: ['$scope', function ($scope) {
                                $scope.offlineData = {};
                                $scope.offlineData.tel = vip_tel;
                                $scope.user = $rootScope.user.UserCode;
                            }]
                    });
                } else if (ret.buttonIndex == 2) {
                    return false;
                }
            });
        };
        //离线会员销售按钮
        $scope.offline_vip = function () {
            apiService('/', {}).success(function (ret) {
                baison_app.api.toast({msg: $rootScope.language.ONLINE_NO_USE_OFFLINEVIP});
                return;
            }).catch(function (e) {
                //弹出录入会员信息页面
                offline_vip_window = ngDialog.open({closeByDocument: false,
                    trapFocus: false,
                    template: './html/cashier/dialog/offline_vip_cashier.html',
                    disableAnimation: true,
                    scope: $scope,
                    controller: ['$scope', function ($scope) {
                            $scope.offlineData = {};
                            $scope.offlineData.tel = '';
                            $scope.user = $rootScope.user.UserCode;
                        }]
                });
            });
        };
        //离线会员销售取消按钮
        $scope.offline_vip_window_close = function () {
            ngDialog.close(offline_vip_window);
        };
        function checkTel(tel)
        {
            var mobile = /^1[3|5|8]\d{9}$/, phone = /^0\d{2,3}-?\d{7,8}$/;
            return mobile.test(tel) || phone.test(tel);
        }
        //离线会员销售确定按钮
        $scope.offline_vip_confirm = function (offlineData) {
            //设置会员相关信息 TODO 导购员问题

            if (!checkTel(offlineData.tel)) {
                baison_app.api.alert({msg: $rootScope.language.TIPS_VIP_TEL_ERROR});
                return;
            }
            var data = {};
            data.vip_code = offlineData.tel; //TODO暂时这么写
            data.customer_code = offlineData.tel; //TODO暂时这么写
            data.customer_name = offlineData.tel; //TODO暂时这么写
            data.customer_tel = offlineData.tel;
            data.customer_integral = '';
            data.rebate = 1;
            GoodsCart.set_current_vip(data);
            $scope.selector = 'sku';
            $scope.selector_class = 'sku';
            ngDialog.close(offline_vip_window);
        };

        //added by lqx maowei on 20170117 屏幕调整高度，不被系统键盘出现所压扁
        var display_adjust = function(){
            var thisHeight = $(window).height();
            $(".cashier_wrap").height(thisHeight - 65);
        }

        display_adjust();

        //根据页面输入查询VIP信息
        var search_vip = function () {
            //判断是否有权限搜索会员
            if ($rootScope.purview['\/CashierIndexCtrl\/search_vip'].show == 0) {
                return;
            }
            baison_app.api.showProgress({
				text: '',
				title: $rootScope.language.TIPS_DATA_NOT_DOWN,
				modal: false
			});
            apiService('/', {}).success(function (ret) {
                VIP.vip_search({vip_code: $scope.input_keyword}).then(function (response) {
                    baison_app.api.hideProgress();
                    if (response.data.status == 1) {
                        var data = response.data.data;
                        if ($rootScope.yxdjsy == "0") {
                            //                        baison_app.api.alert({msg: $rootScope.language.TIPS_CASHIER_USE_WILDERCARD});
                            return;
                        }
                        GoodsCart.set_current_vip(data);
                        //                  //会员输入成功后自动切换回商品
                        $scope.selector = 'sku';
                        $scope.selector_class = 'sku';
                        $rootScope.goods_cart.vip.customer_level = data.customer_level;
                        $scope.input_keyword = '';
                    } else {
                        //$rootScope.goods_cart.vip = {};
                        baison_app.api.toast({msg: $rootScope.language[response.data.message]}); //弹出服务器返回message
                    }
                }).catch(function (err) {
                    //网络故障
                    baison_app.api.toast({msg: $rootScope.language.MSG_NOT_CONNECTED_INTERNET}); //'没有联网'
                });
            }).catch(function (e) {
                //if ($scope.configData.shanghu == 'lqx' || $scope.configData.shanghu == 'lqxtest') {
                    offline_vip_logic($scope.input_keyword);
                    baison_app.api.hideProgress();
                    return;
                //} else {
                //    baison_app.api.toast({msg: $rootScope.language.MSG_NOT_CONNECTED_INTERNET})
                //}
            });
        };
        $scope.jumpAble = 1;
        //根据页面输入查询优惠券信息
        var search_coupon = function () {

            //判断是否有权限搜索优惠券
            if ($rootScope.purview['\/CashierIndexCtrl\/search_coupon'].show == 0) {
                return;
            }
            //判断是否联网
            if (baison_app.api.connectionType == 'none') {
                baison_app.api.toast({msg: $rootScope.language.MSG_NOT_CONNECTED_INTERNET});
                return;
            }
            $scope.jumpAble = 0;
            if ($scope.input_keyword == '') {
                baison_app.api.toast({msg: $rootScope.language.MSG_INPUT_COUPON}); //请输入优惠券券号
                return;
            }
            baison_app.api.showProgress({
				text: '',
				title: $rootScope.language.TIPS_DATA_NOT_DOWN,
				modal: false
			});
            Coupon.coupon_search({coupon: $scope.input_keyword}).then(function (response) {
                baison_app.api.hideProgress();
                //console.log(JSON.stringify(response));
                if (response.data.status == 1) {
                    $scope.cp = response.data.data;
                    if ($scope.cp.detail.end_time < timeStamp2String(new Date(), 'datetime')) {
                        baison_app.api.toast({msg: $rootScope.language.MSG_COUPON_OVER_TIME}); //'该优惠券已过期'
                        return;
                    }
                    window_id = ngDialog.open({closeByDocument: false,
                        trapFocus: false,
                        template: './html/cashier/dialog/coupon.html',
                        disableAnimation: true,
                        scope: $scope
                    });
                    $scope.jumpAble = 1;
                } else {
                    baison_app.api.toast({msg: $rootScope.language[response.data.code]});
                    $scope.jumpAble = 1;
                }
            }).catch(function (err) {
                //网络故障
                baison_app.api.hideProgress();
                baison_app.api.toast({msg: $rootScope.language.MSG_NOT_CONNECTED_INTERNET});
                $scope.jumpAble = 1;
            });
        };
        //事件==============================================================
        //清除输入框内容
        $scope.input_clear = function () {
            if (typeof $scope.input_keyword != 'undefined' || $scope.input_keyword.length != 0) {
                $scope.input_keyword = $scope.input_keyword.substring(0, $scope.input_keyword.length - 1);
            }
        };

        //店长优惠检查
        $scope.checkIsManager = function (type) {
            enquiry = ngDialog.open({closeByDocument: false,
                trapFocus: false,
                template: './html/cashier/keypad/checkManagerSign.html',
                disableAnimation: true,
                scope: $scope,
                controller: [function () {
                        $scope.managerSign = {};
                        $scope.managerSign.manager = $scope.memberManager[0].UserCode;
                        $scope.managerAll = $scope.memberManager;
                    }
                ]
            });
        };


        //店长签名确定
        $scope.confirmManager = function (ret) {
            $scope.memberManager.map(function (x) {
                if (x.UserCode == ret.manager) {
                    $scope.UserSign = x.signatureCode;
                }
            });
            if (typeof ret.sign != 'undefined') {
                if ($scope.UserSign != $.md5(ret.sign)) {
                    baison_app.api.alert({msg: $rootScope.language.TIP_USER_SIGN_WRONG});
                    return;
                }
            } else {
                baison_app.api.alert({msg: $rootScope.language.TIP_USER_SIGN_WRONG});
                return;
            }
            $scope.selector = $scope.managerSelector;
            $scope.btn_enter(2);
            $rootScope.goods_cart.list[$scope.listCount].managerSign = ret;
            ngDialog.close(enquiry);
        };
        //店长签名取消
        $scope.cancelManager = function () {
            $scope.input_keyword = '';
            $scope.selector = 'sku';
            $scope.selector_class = 'sku';
            ngDialog.close(enquiry);
        };
        //店长权限检查
        //取值当，正数为可以优惠的额度
        $scope.manage = function (type, num, price, rebate, money, daogou) {
            if (type == 1) {
                var configData = {};
                $scope.memberGuide.map(function (x) {
                    if (x.UserCode == daogou) {
                        configData = {
                            priceMin: x.minPrice,
                            priceMax: x.maxPrice,
                            moneyMin: 0,
                            moneyMax: x.maxDiscount,
                            rebateMin: x.minRebate,
                            rebateMax: x.maxRebate
                        };
                    }
                });
                if ((($scope.normalPrice - price) >= configData.priceMin) &&
                        (($scope.normalPrice - price) <= configData.priceMax) &&
                        ((($scope.normalPrice * rebate) * num - money) >= configData.moneyMin) &&
                        ((($scope.normalPrice * rebate) * num - money) <= configData.moneyMax) &&
                        (rebate >= configData.rebateMin * 1) &&
                        (rebate <= configData.rebateMax * 1))
                {
                    return 1;
                } else {
                    return 0;
                }
            } else {
                var configData = {};
                $scope.memberManager.map(function (x) {
                    if (x.UserCode == $scope.managerSign.manager) {
                        configData = {
                            priceMin: x.minPrice,
                            priceMax: x.maxPrice,
                            moneyMin: 0,
                            moneyMax: x.maxDiscount,
                            rebateMin: x.minRebate,
                            rebateMax: x.maxRebate
                        };
                    }
                });
                if ((($scope.normalPrice - price) >= configData.priceMin) &&
                        (($scope.normalPrice - price) <= configData.priceMax) &&
                        ((($scope.normalPrice * rebate) * num - money) >= configData.moneyMin) &&
                        ((($scope.normalPrice * rebate) * num - money) <= configData.moneyMax) &&
                        (rebate >= configData.rebateMin * 1) &&
                        (rebate <= configData.rebateMax * 1))
                {
                    return 1;
                } else {
                    return 0;
                }
            }
        };
        //回车按钮点击
        //加一个开关避免重复点击
        $scope.btn_enter_switch = false;
        $scope.btn_enter = function (getType) {

            if ($scope.btn_enter_switch) {
                return;
            } else {
                $scope.btn_enter_switch = true;
            }

            $scope.active_switch = 0.1;
            if ($scope.selector === 'sku') {
                search_goods($scope.input_keyword);
            } else if ($scope.selector === 'vip') {
                search_vip();
            } else if ($scope.selector === 'num') {

                var integral = $scope.input_keyword;
                var re = /^[1-9]+[0-9]*$/;
                if (integral != undefined && integral != null && integral != '') {
                    if (!re.test(integral)) {
                        baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_INPUT_GOODS_NUM}); //请输入正确商品数量
                    } else {
                        var ruleid = $rootScope.goods_cart.list[$scope.listCount].promotionid;
                        var goods_status = $rootScope.goods_cart.list[$scope.listCount].goods_status;

                        if ($rootScope.goods_cart.list[$scope.listCount].promotype == 5 && $rootScope.goods_cart.current_promotions[ruleid] != null && $rootScope.goods_cart.current_promotions[ruleid].is_coupon == 0) {
                            $.each($rootScope.goods_cart.list, function (i, v) {
                                //console.log(v.goods_status);
                                if (v.promotype == 5 && $rootScope.goods_cart.current_promotions[v.promotionid] != null && goods_status == v.goods_status) {
                                    $rootScope.goods_cart.list[i].num = $scope.input_keyword;
                                }
                            });
                            GoodsCart.refresh_cart_num();
                            $scope.animat = "";
                            $scope.btn_enter_switch = false;
                            return;
                        } else if ($rootScope.goods_cart.current_promotions[ruleid] != null) {
                            baison_app.api.toast({msg: $rootScope.language.SP_GIFT_NO_CHANGE_NUM});
                            $scope.animat = "";
                            $scope.btn_enter_switch = false;
                            return;
                        } else {
                            $rootScope.goods_cart.list[$scope.listCount].num = $scope.input_keyword;
                            //GoodsCart.refresh_cart(); TODO cancel_cut_money 有刷新
                        }
                        GoodsCart.cancel_cut_money();
                        //TODO ?????????
                        //get_promotion_gift_goods();
                    }
                }
                $scope.selector = 'sku';
                $scope.selector_class = 'sku';
            } else if ($scope.selector === 'coupon') {
                search_coupon();
            } else if ($scope.selector == 'rebate') {
                $scope.managerSelector = 'rebate';
                var integral = $scope.input_keyword;
                var re = /^[1-9]\d*\.\d*|0\.\d*[1-9]\d*|[1-9]+[0-9]*$/;
                if (integral != undefined && integral != null && integral != '') {
                    if (!re.test(integral)) {
                        baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_INPUT_GOODS_REBATE}); //请输入正确商品折扣
                    } else {
                        if (getType == 2) {
                            var type = '2';
                        } else {
                            var type = '1';
                        }
                        var changenum = $rootScope.goods_cart.list[$scope.listCount].num;
                        var Changeprice = $scope.normalPrice * $scope.input_keyword;
                        var Changerebate = $scope.input_keyword;
                        var Changemoney = Changeprice * $rootScope.goods_cart.list[$scope.listCount].num;
                        var Daogou = $rootScope.goods_cart.list[$scope.listCount].daogou;
                        if ($scope.manage(type, changenum, Changeprice, Changerebate, Changemoney, Daogou) == '0') {
                            if (getType == 2) {
                                $scope.input_keyword = '';
                                $scope.selector = 'sku';
                                $scope.selector_class = 'sku';
                                baison_app.api.alert({msg: $rootScope.language.MSG_MANGER_PURVIER_WARNING_MANAGER});
                            } else {
                                change_rebate = ngDialog.open({closeByDocument: false,
                                    template: './html/component/confirm.html',
                                    disableAnimation: true,
                                    trapFocus: false,
                                    scope: $scope,
                                    preCloseCallback: function () {
                                        $scope.open_windows.pop();
                                    },
                                    controller: [function () {
                                            //标题
                                            $scope.title = $rootScope.language.TIP_CASHIER_TITLE;
                                            //内容
                                            $scope.info = $rootScope.language.MSG_MANGER_PURVIER_WARNING;
                                        }]
                                });
                                $scope.open_windows.push('nothing');
                                //确认
                                $scope.confirm = function () {
                                    $scope.open_windows.pop();
                                    $scope.checkIsManager();
                                    ngDialog.close(change_rebate);
                                };
                                //取消
                                $scope.cancel = function () {
                                    $scope.open_windows.pop();
                                    $scope.input_keyword = '';
                                    $scope.selector = 'sku';
                                    $scope.selector_class = 'sku';
                                    ngDialog.close(change_rebate);
                                };
                            }
                        } else {
                            if (typeof $rootScope.saveMoneyByPrice[$scope.listCount] != 'undefined') {
//                                GoodsCart.refresh_cart()
                                GoodsCart.refresh_cart_num().then(function (ret) {
                                    $rootScope.goods_cart.list[$scope.listCount].rebate = $scope.input_keyword;
                                    $rootScope.goods_cart.list[$scope.listCount].BuyPrice =
                                            $rootScope.goods_cart.list[$scope.listCount].rebate * $rootScope.goods_cart.list[$scope.listCount].SkuPrice;
                                    $rootScope.goods_cart.list[$scope.listCount].money = $rootScope.goods_cart.list[$scope.listCount].BuyPrice *
                                            $rootScope.goods_cart.list[$scope.listCount].num;
                                    $rootScope.saveMoneyByPrice[$scope.listCount] = $rootScope.goods_cart.list[$scope.listCount].SkuPrice *
                                            $rootScope.goods_cart.list[$scope.listCount].num -
                                            $rootScope.goods_cart.list[$scope.listCount].num *
                                            $rootScope.goods_cart.list[$scope.listCount].BuyPrice;
                                    $rootScope.goods_cart.info.discount_money = $rootScope.goods_cart.info.discount_money +
                                            $rootScope.saveMoneyByPrice[$scope.listCount];
                                    $rootScope.goods_cart.info.need_money = $rootScope.goods_cart.info.need_money -
                                            $rootScope.goods_cart.info.discount_money;
                                    GoodsCart.refresh_cart_change();
                                    $scope.input_keyword = '';
                                    $scope.selector = 'sku';
                                    $scope.selector_class = 'sku';
                                });
                            } else {
                                $rootScope.goods_cart.list[$scope.listCount].rebate = $scope.input_keyword;
                                $rootScope.goods_cart.list[$scope.listCount].BuyPrice =
                                        $rootScope.goods_cart.list[$scope.listCount].rebate * $rootScope.goods_cart.list[$scope.listCount].SkuPrice;
                                $rootScope.goods_cart.list[$scope.listCount].money = $rootScope.goods_cart.list[$scope.listCount].BuyPrice *
                                        $rootScope.goods_cart.list[$scope.listCount].num;
                                $rootScope.saveMoneyByPrice[$scope.listCount] = $rootScope.goods_cart.list[$scope.listCount].SkuPrice *
                                        $rootScope.goods_cart.list[$scope.listCount].num -
                                        $rootScope.goods_cart.list[$scope.listCount].num *
                                        $rootScope.goods_cart.list[$scope.listCount].BuyPrice;
                                $rootScope.goods_cart.info.discount_money = $rootScope.goods_cart.info.discount_money +
                                        $rootScope.saveMoneyByPrice[$scope.listCount];
                                $rootScope.goods_cart.info.need_money = $rootScope.goods_cart.info.need_money -
                                        $rootScope.goods_cart.info.discount_money;
                                GoodsCart.refresh_cart_change();
                                $scope.input_keyword = '';
                                $scope.selector = 'sku';
                                $scope.selector_class = 'sku';
                            }
                        }
                    }
                }
//                $scope.selector = 'sku';
//                $scope.selector_class = 'sku';
////                $scope.input_keyword = '';
            } else if ($scope.selector == 'price') {
                $scope.managerSelector = 'price';
                var integral = $scope.input_keyword;
                var re = /^[1-9]\d*\.\d*|0\.\d*[1-9]\d*|[1-9]+[0-9]*$/;
                if (integral != undefined && integral != null && integral != '') {
                    if (!re.test(integral)) {
                        baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_INPUT_GOODS_PRICE}); //请输入正确商品单价
                    } else {
                        //注意加减sunpcm
                        if (getType == 2) {
                            var type = '2';
                        } else {
                            var type = '1';
                        }
                        var changenum = $rootScope.goods_cart.list[$scope.listCount].num;
                        var Changeprice = $scope.input_keyword;
                        var Changerebate = Changeprice / $scope.normalPrice;
                        var Changemoney = Changeprice * $rootScope.goods_cart.list[$scope.listCount].num;
                        var Daogou = $rootScope.goods_cart.list[$scope.listCount].daogou;
                        if ($scope.manage(type, changenum, Changeprice, Changerebate, Changemoney, Daogou) == '0') {
                            if (getType == 2) {
                                $scope.input_keyword = '';
                                $scope.selector = 'sku';
                                $scope.selector_class = 'sku';
                                baison_app.api.alert({msg: $rootScope.language.MSG_MANGER_PURVIER_WARNING_MANAGER});
                                //return;
                            } else {
                                change_price = ngDialog.open({closeByDocument: false,
                                    template: './html/component/confirm.html',
                                    disableAnimation: true,
                                    trapFocus: false,
                                    scope: $scope,
                                    preCloseCallback: function () {
                                        $scope.open_windows.pop();
                                    },
                                    controller: [function () {
                                            //标题
                                            $scope.title = $rootScope.language.TIP_CASHIER_TITLE;
                                            //内容
                                            $scope.info = $rootScope.language.MSG_MANGER_PURVIER_WARNING;
                                        }]
                                });
                                $scope.open_windows.push('nothing');
                                //确认
                                $scope.confirm = function () {
                                    $scope.open_windows.pop();
                                    $scope.checkIsManager();
                                    ngDialog.close(change_price);
                                };
                                //取消
                                $scope.cancel = function () {
                                    $scope.open_windows.pop();
                                    $scope.input_keyword = '';
                                    $scope.selector = 'sku';
                                    $scope.selector_class = 'sku';
                                    ngDialog.close(change_price);
                                };
                            }
                        } else {
                            if (typeof $rootScope.saveMoneyByPrice[$scope.listCount] != 'undefined') {
//                                GoodsCart.refresh_cart();
                                GoodsCart.refresh_cart_num().then(function (ret) {
                                    $rootScope.goods_cart.list[$scope.listCount].BuyPrice = $scope.input_keyword;
                                    $rootScope.goods_cart.list[$scope.listCount].money = $rootScope.goods_cart.list[$scope.listCount].BuyPrice *
                                            $rootScope.goods_cart.list[$scope.listCount].num;
                                    $rootScope.goods_cart.list[$scope.listCount].rebate =
                                            $rootScope.goods_cart.list[$scope.listCount].BuyPrice / $rootScope.goods_cart.list[$scope.listCount].SkuPrice;
                                    $rootScope.saveMoneyByPrice[$scope.listCount] = $rootScope.goods_cart.list[$scope.listCount].SkuPrice *
                                            $rootScope.goods_cart.list[$scope.listCount].num -
                                            $rootScope.goods_cart.list[$scope.listCount].num *
                                            $rootScope.goods_cart.list[$scope.listCount].BuyPrice;
                                    $rootScope.goods_cart.info.discount_money = $rootScope.goods_cart.info.discount_money +
                                            $rootScope.saveMoneyByPrice[$scope.listCount];
                                    $rootScope.goods_cart.info.need_money = $rootScope.goods_cart.info.need_money -
                                            $rootScope.goods_cart.info.discount_money;
                                    GoodsCart.refresh_cart_change();
                                    $scope.input_keyword = '';
                                    $scope.selector = 'sku';
                                    $scope.selector_class = 'sku';
                                });
                            } else {
                                $rootScope.goods_cart.list[$scope.listCount].BuyPrice = $scope.input_keyword;
                                $rootScope.goods_cart.list[$scope.listCount].money = $rootScope.goods_cart.list[$scope.listCount].BuyPrice *
                                        $rootScope.goods_cart.list[$scope.listCount].num;
                                $rootScope.goods_cart.list[$scope.listCount].rebate =
                                        $rootScope.goods_cart.list[$scope.listCount].BuyPrice / $rootScope.goods_cart.list[$scope.listCount].SkuPrice;
                                $rootScope.saveMoneyByPrice[$scope.listCount] = $rootScope.goods_cart.list[$scope.listCount].SkuPrice *
                                        $rootScope.goods_cart.list[$scope.listCount].num -
                                        $rootScope.goods_cart.list[$scope.listCount].num *
                                        $rootScope.goods_cart.list[$scope.listCount].BuyPrice;
                                $rootScope.goods_cart.info.discount_money = $rootScope.goods_cart.info.discount_money +
                                        $rootScope.saveMoneyByPrice[$scope.listCount];
                                $rootScope.goods_cart.info.need_money = $rootScope.goods_cart.info.need_money -
                                        $rootScope.goods_cart.info.discount_money;
                                GoodsCart.refresh_cart_change();
                                $scope.input_keyword = '';
                                $scope.selector = 'sku';
                                $scope.selector_class = 'sku';
                            }
                        }
                    }
                }
//                $scope.selector = 'sku';
//                $scope.selector_class = 'sku';
//                $scope.input_keyword = '';
            } else if ($scope.selector == 'money') {
                $scope.managerSelector = 'money';
                var integral = $scope.input_keyword;
                var re = /^[1-9]\d*\.\d*|0\.\d*[1-9]\d*|[1-9]+[0-9]*$/;
                if (integral != undefined && integral != null && integral != '') {
                    if (!re.test(integral)) {
                        baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_INPUT_GOODS_MONEY}); //请输入正确商品总价
                    } else {
                        if (getType == 2) {
                            var type = '2';
                        } else {
                            var type = '1';
                        }
                        var changenum = $rootScope.goods_cart.list[$scope.listCount].num;
                        var Changeprice = $scope.input_keyword / changenum;
                        var Changerebate = Changeprice / $scope.normalPrice;
                        var Changemoney = $scope.input_keyword;
                        var Daogou = $rootScope.goods_cart.list[$scope.listCount].daogou;
                        if ($scope.manage(type, changenum, Changeprice, Changerebate, Changemoney, Daogou) == '0') {
                            if (getType == 2) {
                                $scope.input_keyword = '';
                                $scope.selector = 'sku';
                                $scope.selector_class = 'sku';
                                baison_app.api.alert({msg: $rootScope.language.MSG_MANGER_PURVIER_WARNING_MANAGER});
                            } else {
                                change_money = ngDialog.open({closeByDocument: false,
                                    template: './html/component/confirm.html',
                                    disableAnimation: true,
                                    trapFocus: false,
                                    scope: $scope,
                                    preCloseCallback: function () {
                                        $scope.open_windows.pop();
                                    },
                                    controller: [function () {
                                            //标题
                                            $scope.title = $rootScope.language.TIP_CASHIER_TITLE;
                                            //内容
                                            $scope.info = $rootScope.language.MSG_MANGER_PURVIER_WARNING;
                                        }]
                                });
                                $scope.open_windows.push('nothing');
                                //确认
                                $scope.confirm = function () {
                                    $scope.open_windows.pop();
                                    $scope.checkIsManager();
                                    ngDialog.close(change_money);
                                };
                                //取消
                                $scope.cancel = function () {
                                    $scope.open_windows.pop();
                                    $scope.input_keyword = '';
                                    $scope.selector = 'sku';
                                    $scope.selector_class = 'sku';
                                    ngDialog.close(change_money);
                                };

                            }
                        } else {
                            if (typeof $rootScope.saveMoneyByPrice[$scope.listCount] != 'undefined') {
                                GoodsCart.refresh_cart_num().then(function (ret) {
                                    $rootScope.goods_cart.list[$scope.listCount].money = $scope.input_keyword;
                                    $rootScope.goods_cart.list[$scope.listCount].BuyPrice = $rootScope.goods_cart.list[$scope.listCount].money /
                                            $rootScope.goods_cart.list[$scope.listCount].num;
                                    $rootScope.goods_cart.list[$scope.listCount].rebate =
                                            $rootScope.goods_cart.list[$scope.listCount].BuyPrice / $rootScope.goods_cart.list[$scope.listCount].SkuPrice;
                                    $rootScope.saveMoneyByPrice[$scope.listCount] = $rootScope.goods_cart.list[$scope.listCount].SkuPrice *
                                            $rootScope.goods_cart.list[$scope.listCount].num -
                                            $rootScope.goods_cart.list[$scope.listCount].num *
                                            $rootScope.goods_cart.list[$scope.listCount].BuyPrice;
                                    $rootScope.goods_cart.info.discount_money = $rootScope.goods_cart.info.discount_money +
                                            $rootScope.saveMoneyByPrice[$scope.listCount];
                                    $rootScope.goods_cart.info.need_money = $rootScope.goods_cart.info.need_money -
                                            $rootScope.goods_cart.info.discount_money;
                                    GoodsCart.refresh_cart_change();
                                    $scope.input_keyword = '';
                                    $scope.selector = 'sku';
                                    $scope.selector_class = 'sku';
                                });
                            } else {
                                $rootScope.goods_cart.list[$scope.listCount].money = $scope.input_keyword;
                                $rootScope.goods_cart.list[$scope.listCount].BuyPrice = $rootScope.goods_cart.list[$scope.listCount].money /
                                        $rootScope.goods_cart.list[$scope.listCount].num;
                                $rootScope.goods_cart.list[$scope.listCount].rebate =
                                        $rootScope.goods_cart.list[$scope.listCount].BuyPrice / $rootScope.goods_cart.list[$scope.listCount].SkuPrice;
                                $rootScope.saveMoneyByPrice[$scope.listCount] = $rootScope.goods_cart.list[$scope.listCount].SkuPrice *
                                        $rootScope.goods_cart.list[$scope.listCount].num -
                                        $rootScope.goods_cart.list[$scope.listCount].num *
                                        $rootScope.goods_cart.list[$scope.listCount].BuyPrice;
                                $rootScope.goods_cart.info.discount_money = $rootScope.goods_cart.info.discount_money +
                                        $rootScope.saveMoneyByPrice[$scope.listCount];
                                $rootScope.goods_cart.info.need_money = $rootScope.goods_cart.info.need_money -
                                        $rootScope.goods_cart.info.discount_money;
                                GoodsCart.refresh_cart_change();
                                $scope.input_keyword = '';
                                $scope.selector = 'sku';
                                $scope.selector_class = 'sku';
                            }
                        }
                    }
                }
//                $scope.selector = 'sku';
//                $scope.selector_class = 'sku';
//                $scope.input_keyword = '';
            }
//            $scope.input_keyword = '';
            $scope.animat = "";
            $scope.btn_enter_switch = false;
        };
        //更改购物车商品数量
        $scope.active_switch = 0.1;
        $scope.changeGoodsNum = function (count) {
            //判断是否有权限
            if ($rootScope.purview['\/CashierIndexCtrl\/changeGoodsNum'].show == 0) {
                return;
            }
            $scope.selector_class = 'num';
            $scope.selector = 'num';
            $scope.listCount = count;
            $scope.id = 1;
            $scope.active_switch = count + 'num';
            $scope.animat = "flashes";
        };
        //修改折扣
        $scope.changeGoodsRebate = function (count) {
            if ($rootScope.purview['\/CashierIndexCtrl\/changeGoodsRebate'].show == '0') {
                return;
            }
            BaseGoods.get_sku_by_code($rootScope.goods_cart.list[count].SkuCode).then(function (ret) {
                $scope.normalPrice = ret[0].SkuPrice;
                $scope.selector_class = 'rebate';
                $scope.selector = 'rebate';
                $scope.listCount = count;
                $scope.id = 1;
                $scope.active_switch = count + 'rebate';
                $scope.animat = "flashes";
            });
        };
        //修改单价
        $scope.changeGoodsPrice = function (count) {
            if ($rootScope.purview['\/CashierIndexCtrl\/changeGoodsPrice'].show == '0') {
                return;
            }
            BaseGoods.get_sku_by_code($rootScope.goods_cart.list[count].SkuCode).then(function (ret) {
                $scope.normalPrice = ret[0].SkuPrice;
                $scope.selector_class = 'price';
                $scope.selector = 'price';
                $scope.listCount = count;
                $scope.id = 1;
                $scope.active_switch = count + 'price';
                $scope.animat = "flashes";
            });
        };
        //修改金额
        $scope.changeGoodsMoney = function (count) {
            if ($rootScope.purview['\/CashierIndexCtrl\/changeGoodsMoney'].show == '0') {
                return;
            }
            BaseGoods.get_sku_by_code($rootScope.goods_cart.list[count].SkuCode).then(function (ret) {
                $scope.normalPrice = ret[0].SkuPrice;
                $scope.selector_class = 'money';
                $scope.selector = 'money';
                $scope.listCount = count;
                $scope.id = 1;
                $scope.active_switch = count + 'money';
                $scope.animat = "flashes";
            });
        };
        //选中商品列表项
        $scope.check_switch = 0;
        $scope.checkToggle = function (count) {
            $scope.check_switch = count;
        };
        //数字按钮点击
        /***
         $interval(function () {
         $scope.animate_class = {};
         }, 60);
         ***/

        $scope.btn_number = function (number,$event) {
            $scope.input_keyword = String($scope.input_keyword) + String(number);
        };
        //清空当前输入框
        $scope.inputClearAll = function(){
            $scope.input_keyword = '';
        }
        //购物车删除按钮
        $scope.goods_cart_remove = function (i) {
            GoodsCart.delete_from_cart(i);
        };
        //pc版购物车删除
        $scope.delete_goods_cart = function (i) {
            $scope.goods_cart_remove(i);
        };
        //取消交易按钮（清空购物车）
        $scope.goods_cart_clear = function () {
            //判断是否有权限
            if ($rootScope.purview['\/cancel'].show == 0) {
                return;
            }
            $rootScope.saveMoneyByPrice = []
            GoodsCart.clear_cart();
        };
        //切换VIP和商品
        $scope.animat_p = "";
        $scope.change_selector = function () {
            if ($scope.selector == 'sku') {
                $scope.selector = 'vip';
                $scope.selector_class = '';
            } else {
                $scope.selector = 'sku';
                $scope.selector_class = 'sku';
            }
            $scope.input_keyword = '';
            if ($scope.animat_p == "") {
                $scope.animat_p = "rotateX";
            } else {
                $scope.animat_p = "";
            }

            $scope.focus();
        };
        //优惠券查询
        $scope.search_coupon = function () {
            $scope.input_keyword = '';
            //判断是否有优惠券查询权限
            if ($rootScope.purview['\/CashierIndexCtrl\/search_coupon'].show == '0') {
                return;
            }
            $scope.selector = 'coupon';
            if ($scope.animat_p == "") {
                $scope.animat_p = "rotateX";
            } else {
                $scope.animat_p = "";
            }
        };
        //判断是否可以与促销折上折
        var check_use_coupon_by_promotion = function () {
            var add_profits = true;
            $.each($rootScope.goods_cart.current_promotions, function (i, n) {
                if (n.isUse) {
                    if (n.is_added_profits == 0) {
                        add_profits = false;
                    }
                }

            });
            return add_profits;
        };
        //判断是否可以与vip折上折
        var check_use_coupon_by_vip = function () {


        };

        //判断绑定促销的优惠券是否可以（多张）使用
        var check_coupon_use_more = function (promotion) {
            var use = true;
            if ($rootScope.goods_cart.couponData[promotion.promotion_rule_id] != undefined && promotion.is_use_more == 0) {
                use = false;
                baison_app.api.alert({msg: $rootScope.language.MSG_COUPON_NO_USE_MORE});
            }

            return use;
        };

        //点击优惠券使用
        $scope.use_coupon = function () {
            var coupon = $scope.cp.coupon;
            var coupon_detail = $scope.cp.detail;
            if(coupon_detail['is_accept'] == 0){
                baison_app.api.toast({msg:  $rootScope.language.MSG_NO_SEND_NO_USECOUPON}); //
                ngDialog.close(window_id);
                return ;
            }
            if(coupon_detail['customer_code'] != ''){
                if($rootScope.goods_cart.vip.vip_code == ''){
                    baison_app.api.toast({msg: $rootScope.language.TIPS_CASHIER_INPUT_RIGHT_TEL}); //
                    ngDialog.close(window_id);
                    return;
                }else if($rootScope.goods_cart.vip.customer_code != coupon_detail['customer_code'] ){
                    baison_app.api.toast({msg: $rootScope.language.TIPS_CASHIER_INPUT_RIGHT_TEL}); //
                    ngDialog.close(window_id);
                    return;
                }

            }
            //不与促销关联的优惠券，必须先选择商品
            //if (coupon.promo_id == '') {
            if ($rootScope.goods_cart.list.length == 0) {
                baison_app.api.toast({msg: $rootScope.language.MSG_NO_GOODS_NO_USECOUPON}); //
                ngDialog.close(window_id);
                return;
            }
            //}
            //当前时间
            var day = timeStamp2String(new Date(), 'datetime');
            //判断优惠券是否使用过
            if (coupon_detail.is_use == 1) {
                baison_app.api.toast({msg: $rootScope.language.MSG_COUPON_IS_USE}); //该优惠券已使用过
                ngDialog.close(window_id);
                return;
            }
            //判断优惠券是否被作废
            if (coupon_detail.is_cancel == 1) {
                baison_app.api.toast({msg: $rootScope.language.MSG_COUPON_IS_INVALID}); //优惠券已被作废
                ngDialog.close(window_id);
                return;
            }
            //判断优惠券是否被占用
            /*
             if (coupon_detail.is_occupy == 1) {
             baison_app.api.toast({msg: $rootScope.language.MSG_COUPON_IS_OCCUPY}); //优惠券已被占用
             ngDialog.close(window_id);
             return;
             }
             */
            if (coupon_detail.vip_code != '' && coupon_detail.vip_code != $rootScope.goods_cart.vip.vip_code && coupon_detail.is_accept == 1) {
                baison_app.api.toast({msg: $rootScope.language.MSG_COUPON_IS_USE_HAVENT_ROOT}); //优惠券已被领用，你没有权限使用
                ngDialog.close(window_id);
                return;
            }

            //判断是否在优惠券的使用时间内
            if (typeof coupon_detail.start_time !== 'string' || typeof coupon_detail.end_time !== 'string') {
                var start_time = timeStamp2String(coupon_detail.start_time, 'datetime');
                var end_time = timeStamp2String(coupon_detail.end_time, 'datetime');
                if (!(start_time <= day && end_time >= day)) {
                    baison_app.api.toast({msg: $rootScope.language.MSG_COUPON_IS_OVER_TIME}); //该优惠券不在使用日期内
                    ngDialog.close(window_id);
                    return;
                }
            }

//			if(!check_use_coupon_by_promotion()){
//				baison_app.api.toast({msg:'该优惠券不在使用范围'}); //该优惠券不在使用日期内
//				return;
//			}
//			
            $scope.availCoupon = {};
            //根据优惠券的促销id来获取促销信息 
            //优惠券未绑定促销
            if (coupon.promo_id == '') {
                //若是抵扣券

                if (coupon.type == 0 || coupon.type == 3) {

                    //判断是否是会员才能使用的抵扣券和折扣券
                    if (coupon_detail.vip_code != '') {
                        if ($rootScope.goods_cart.vip.vip_code != coupon_detail.vip_code) {
                            baison_app.api.toast({msg: $rootScope.language.MSG_SORRY_CANT_USE_SELECT_VIP}); //'对不起，无法使用,请选择会员'
                            ngDialog.close(window_id);
                            return;
                        }
                    }
                    var money = parseFloat($scope.cp.coupon.money);
                    var coupon_code = $scope.cp.detail.coupon_code;
                    //TODO 结算页面优惠券的抵扣金额大于总金额需要再处理
                    var final_money = (money > $rootScope.goods_cart.info.total_money && $rootScope.goods_cart.info.total_money > 0) ? $rootScope.goods_cart.info.total_money : money;
                    final_money = parseFloat(final_money);
                    //修改随机券 不能使用问题
//                  if ($rootScope.goods_cart.info.total_money < money) {
//                      baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_INCONFORMITY_DEDUCTION}); //不符合抵扣券
//                      ngDialog.close(window_id);
//                      return;
//                  }
                    var remark = $rootScope.language.MSG_COUPON + '：' + coupon_code + $rootScope.language.MSG_DENOMINATION + money; //优惠券：  ；面额：
                    money = (money > $rootScope.goods_cart.info.total_money && $rootScope.goods_cart.info.total_money > 0) ? $rootScope.goods_cart.info.total_money : money;
                    //添加数据
                    GoodsCart.add_check('003', $rootScope.language.MSG_COUPON, money, final_money, coupon_code, remark);

                    ngDialog.close(window_id);

                    baison_app.api.toast({msg: $rootScope.language.MSG_COUPON_ADD_SUCCESS}); //'优惠券添加成功'
                    return;
                }
                //会员使用的优惠券
                if (coupon_detail.vip_code != '') {
                    if ($rootScope.goods_cart.vip.vip_code != coupon_detail.vip_code) {
                        baison_app.api.toast({msg: $rootScope.language.MSG_SORRY_CANT_USE_SELECT_VIP}); //'对不起，无法使用,请选择会员'
                        ngDialog.close(window_id);
                        return;
                    } else {
                        //判断优惠券类型
//                      switch (coupon.type) {
//                          case '1':  //折扣券
//                              $scope.availCoupon.rebate = coupon.rebate;
//                              $scope.availCoupon.type = coupon.type;
//                              break;
//                          case '2':   //赠券(需要绑定促销策略)
//                          case '3':  //随机金额券
//                              $scope.availCoupon.money = coupon_detail.money;
//                              $scope.availCoupon.type = coupon.type;
//                              break;
//                      }
                        GoodsCart.add_to_couponData(coupon, coupon_detail);//, $scope.availCoupon, {}
                    }
                } else {
                    //优惠券所有人都可以使用，判断优惠券类型
                    //判断优惠券类型
//                  switch (coupon.type) {
//                      case '1':  //折扣券
//                          $scope.availCoupon.rebate = coupon.rebate;
//                          $scope.availCoupon.type = coupon.type;
//                          break;
//                      case '2':   //赠券（绑定促销策略）
//                      case '3':  //随机金额券
//                          $scope.availCoupon.money = coupon_detail.money;
//                          $scope.availCoupon.type = coupon.type;
//                          break;
//                  }
                    GoodsCart.add_to_couponData(coupon, coupon_detail);
                }
            } else {
                //优惠券绑定促销活动   满额打折成功    满额减钱成功   满件减钱成功    （满额减件  满件减件）未测
                //判断优惠券是否是发放给当前会员使用
                if (typeof coupon_detail.vip_code == 'string' && coupon_detail.vip_code != '') {
                    //会员使用
                    if ($rootScope.goods_cart.vip.vip_code != coupon_detail.vip_code) {
                        baison_app.api.toast({msg: $rootScope.language.MSG_SORRY_CANT_USE}); //'对不起，无法使用'
                        ngDialog.close(window_id);
                        return;
                    }
                    //绑定促销的优惠券所有人都可以使用
                    //判断该优惠券是否可以多张使用
                    Promotion.getPromotionRule_by_promo_id(coupon.promo_id).then(function (ret) {
                        if (!check_coupon_use_more(ret[0])) {
                            return;
                        }
                        //直接使用记录优惠券
                        GoodsCart.add_to_couponData(coupon, coupon_detail);
                        if ($rootScope.goods_cart.list.length == 0) {
                            return;
                        }
                        if ($rootScope.goods_cart.current_promotions[coupon.promo_id] != undefined) {
                            return;
                        }
                        //绑定可用促销
                        Promotion.get_available_promotion().then(function (success) {
                            if ($rootScope.goods_cart.available_promotions[coupon.promo_id] != undefined) {
                                var detail = $rootScope.goods_cart.available_promotions[coupon.promo_id];
                                if (detail.promotion_type == 1 || detail.promotion_type == 3) {//满额赠件
                                    get_gift_goods(detail);
                                } else {
                                    GoodsCart.add_current_promotion(detail);
                                }
                            }
                        });
                    });

                } else {
                    //绑定促销的优惠券所有人都可以使用
                    //判断该优惠券是否可以多张使用
                    Promotion.getPromotionRule_by_promo_id(coupon.promo_id).then(function (ret) {
                        if (!check_coupon_use_more(ret[0])) {
                            return;
                        }
                        //直接使用记录优惠券
                        GoodsCart.add_to_couponData(coupon, coupon_detail);
                        if ($rootScope.goods_cart.list.length == 0) {
                            return;
                        }
                        if ($rootScope.goods_cart.current_promotions[coupon.promo_id] != undefined) {
                            return;
                        }
                        //绑定可用促销
                        Promotion.get_available_promotion().then(function (success) {
                            if ($rootScope.goods_cart.available_promotions[coupon.promo_id] != undefined) {
                                var detail = $rootScope.goods_cart.available_promotions[coupon.promo_id];
                                if (detail.promotion_type == 1 || detail.promotion_type == 3) {//满额赠件
                                    get_gift_goods(detail);
                                } else {
                                    GoodsCart.add_current_promotion(detail);
                                }
                            }
                        });
                    });
                }
            }

            ngDialog.close(window_id);
        };
        //优惠券删除
        $scope.couponData_remove = function (i, pid, promotion) {
            //不绑定促销的优惠券
            if (pid == '') {
                GoodsCart.delete_from_couponData(i, pid);
            } else {
                GoodsCart.delete_from_couponData(i, pid);
            }

        };
        //会员发卡按钮点击
        $scope.add_vip = function () {
            //权限检查
            if ($rootScope.purviewCheckChange('\/CashierIndexCtrl\/add_vip')) {
                return;
            }
            $location.path('/member/add');
        };
        //将弹框内的输入数据抛出
        $scope.change_input_stock_query = function (val) {
            $scope.input_keyword_inv = val;
        };
//**********************************************************************************************************************************************************************************************************


        //查库存功能
        //本店
        $scope.cur_shop = function () {
            $scope.inventoryGoods = [];
            $scope.cur = 0;
            $scope.cur_select = "";
            $scope.searchNearly = false;
        };
        //邻店
        $scope.nearly_shop = function () {
            $scope.inventoryGoods = [];
            $scope.cur = 1;
            $scope.cur_select = $rootScope.language.TIPS_CASHIER_NEARELY_SHOP;
            $scope.searchNearly = true;
            ShopGetFriend().then(function (ret) {
                if (ret.data.status == 1) {
                    $scope.ShopFriend = [];
                    ret.data.data.forEach(function (n) {
                        if (n.friend_shop_code != $rootScope.current_shop.ShopCode) {
                            $scope.ShopFriend.push(n);
                        }
                    });
                    if (ret.data.data.length == 0) {
                        $scope.shop_name = '';
                    } else {
                        $scope.shop_name = ret.data.data[0].friend_shop_code;
                    }
                } else {
                    $scope.ShopFriend = [];
                    baison_app.api.toast({msg: $rootScope.language.TIP_CASHIER_MESSAGE_GET});
                }
            });
        };
//        //总店
//        $scope.all_shop = function () {
//            $scope.cur = 2;
//        };
        //清空库存查询数据
        $scope.clearInventory = function () {
            ngDialog.close(enquiry);
            $scope.inventoryGoods = [];
            $scope.input_keyword_inv = '';
            $scope.input_keyword = '';
            enquiry = ngDialog.open({closeByDocument: false,
                trapFocus: false,
                template: './html/cashier/keypad/enquiry_inventory.html',
                disableAnimation: true,
                scope: $scope,
                preCloseCallback: function () {
                    $scope.open_windows.pop();
                }
            });
        };
        //本店查询按钮
        $scope.searchInventory = function (input_keyword, cur, shop_name) {

            $scope.nearshop_name = shop_name;
            $scope.cur = cur;
//            baison_app.api.alert({msg:cur});

            if ('' == input_keyword || input_keyword.length < 3) {
                baison_app.api.toast({
                    msg: $rootScope.language.MSG_INPUT_MORE_THREE
                }); //'请至少输入三位'
                return;
            }
            baison_app.api.toast({msg: $rootScope.language.TIPS_SEARCHING}); //'查询中...'
            if ($scope.cur == 0) {
                BaseGoods.get_sku_by_code(input_keyword).then(function (sku) {
                    if (sku.length == 0) {
                        $scope.clearInventory();
                        baison_app.api.toast({msg: $rootScope.language.MSG_CANT_FOUND_GOODS}); //'没有找到商品'
                    } else if (sku.length == 1) {
                        $scope.inventoryGoods = sku;
                    } else if (sku.length <= $scope.suk_num_max) {
                        $scope.goods_select_data = sku;
                        $scope.goods_select_data_choose = 0;
                        window_cur = ngDialog.open({closeByDocument: false,
                            trapFocus: false,
                            template: './html/cashier/keypad/goods_select_stock.html',
                            disableAnimation: true,
                            scope: $scope,
                            preCloseCallback: function () {
                                $scope.open_windows.pop();
                            }
                        });
                        $scope.open_windows.push('goods_select_stock');
                        //商品选择器
                        $scope.goods_select_stock = function (sku) {
                            var new_sku = {};
                            new_sku [0] = sku;
                            $scope.inventoryGoods = new_sku;
                            ngDialog.close(window_cur.id);
                        };
                    } else {
                        $scope.clearInventory();
                        baison_app.api.toast({msg: $rootScope.language.MSG_GOODS_MANY_INPUT_MORE_CODE}); //'查到的商品太多，请输入更完整的条码'
                    }
                }, function (err) {
                    baison_app.api.toast({msg: err});
                });
            }

            //私有方法 邻店查询
            var getStockNumAndRoadNum_by = function (goods_code, shop_code) {
                BaseGoods.getStockNumAndRoadNum_by_shopCode_skus(goods_code, shop_code).then(function (ret) {
                    if (typeof ret.data.data == 'undefined') {
                        $scope.clearInventory();
                        baison_app.api.toast({msg: $rootScope.language.MSG_CANT_FOUND_GOODS}); //'没有找到商品'
                    } else if (ret.data.data.length == 0) {
                        $scope.clearInventory();
                        baison_app.api.toast({msg: $rootScope.language.MSG_CANT_FOUND_GOODS}); //'没有找到商品'
                    } else if (ret.data.data.length <= 5) {
                        $scope.inventoryGoods = ret.data.data;
                    } else {
                        $scope.clearInventory();
                        baison_app.api.toast({msg: $rootScope.language.MSG_GOODS_MANY_INPUT_MORE_CODE}); //'查到的商品太多，请输入更完整的条码'
                    }
                }, function (err) {
                    baison_app.api.toast({msg: err});
                });
            };
            //邻店查询按钮
            if ($scope.cur == 1) {
                var shopCode = ''; //'D2Q2D0081DR';
                var GoodsCode = ''; //'D2Q2D0081DR';
                if (typeof $scope.ShopFriend == 'undefined') {
                    shopCode = '';
                } else {
                    shopCode = $scope.shop_name;
                }
                if ($scope.nearshop_name == '' || typeof $scope.nearshop_name == 'undefined') {
                    baison_app.api.toast({msg: $rootScope.language.TIP_SETTING_CHOSE_SHOP});
                    return;
                }
                BaseGoods.get_sku_by_code(input_keyword).then(function (sku) {
                    if (sku.length == 0) {
                        $scope.clearInventory();
                        baison_app.api.toast({msg: $rootScope.language.MSG_CANT_FOUND_GOODS}); //'没有找到商品'
                    } else if (sku.length == 1) {
                        getStockNumAndRoadNum_by(sku[0].SkuCode, $scope.nearshop_name);
                    } else if (sku.length <= $scope.suk_num_max) {
                        $scope.goods_select_data = sku;
                        $scope.goods_select_data_choose = 0;
                        window_cur = ngDialog.open({closeByDocument: false,
                            trapFocus: false,
                            template: './html/cashier/keypad/goods_select_stock.html',
                            disableAnimation: true,
                            scope: $scope,
                            preCloseCallback: function () {
                                $scope.open_windows.pop();
                            }
                        });
                        $scope.open_windows.push('goods_select_stock');
                        //商品选择器
                        $scope.goods_select_stock = function (sku) {
                            var new_sku = {};
                            new_sku [0] = sku;
                            $scope.inventoryGoods = new_sku;
                            getStockNumAndRoadNum_by($scope.inventoryGoods[0].SkuCode, $scope.nearshop_name);
                            ngDialog.close(window_cur.id);
                        };
                    } else {
                        $scope.clearInventory();
                        baison_app.api.toast({msg: $rootScope.language.MSG_GOODS_MANY_INPUT_MORE_CODE}); //'查到的商品太多，请输入更完整的条码'
                    }
                }, function (err) {
                    baison_app.api.toast({msg: err});
                });


//                BaseGoods.getStockNumAndRoadNum_by_shopCode_skus(input_keyword, shop_name).then(function (sku) {
//                    if (sku.data.data.length == 0) {
//                        $scope.clearInventory();
//                        baison_app.api.toast({msg: $rootScope.language.MSG_CANT_FOUND_GOODS}); //'没有找到商品'
//                    } else if (sku.data.data.length == 1) {
//                        $scope.inventoryGoods = sku.data.data;
//                    } else if (sku.data.data.length <= 5) {
//                        $scope.goods_select_data = sku;
//                        $scope.goods_select_data_choose = 0;
//                        window_cur = ngDialog.open({closeByDocument: false,
//                            trapFocus: false,
//                            template: './html/cashier/keypad/goods_select_stock.html',
//                            disableAnimation: true,
//                            scope: $scope,
//                            preCloseCallback: function () {
//                                $scope.open_windows.pop();
//                            }
//                        });
//                        $scope.open_windows.push('goods_select_stock');
//                        //商品选择器
//                        $scope.goods_select_stock = function (sku) {
//                            var new_sku = {};
//                            new_sku [0] = sku;
//                            getStockNumAndRoadNum_by(sku.GoodsCode, shopCode);
//                            ngDialog.close(window_cur.id);
//                        };
//                    } else {
//                        $scope.clearInventory();
//                        baison_app.api.toast({msg: $rootScope.language.MSG_GOODS_MANY_INPUT_MORE_CODE}); //'查到的商品太多，请输入更完整的条码'
//                    }
//                }, function (err) {
//                    baison_app.api.toast({msg: err});
//                });
            }
        };
        //如果输入框是不是空就 打开库存查询
        if ($scope.input_keyword != '') {
            var cur = $scope.cur;
            $scope.input_keyword_inv = input_keyword;
            $scope.searchInventory(input_keyword, cur);
        }
//*******************************************************************************************
        $scope.referInventory = function () {
            var input_keyword = $scope.input_keyword;
            $scope.more_btns_active = '';
            //权限检查
            if ($rootScope.purviewCheckChange('\/CashierIndexCtrl\/referInventory')) {
                return;
            }
            $scope.cur = 0;
            enquiry = ngDialog.open({closeByDocument: false,
                trapFocus: false,
                template: './html/cashier/keypad/enquiry_inventory.html',
                disableAnimation: true,
                scope: $scope,
                preCloseCallback: function () {
                    $scope.open_windows.pop();
                }
            });
            $scope.open_windows.push('enquiry_selector');
            $scope.focus("enquiry_input");
        };
        //整单备注点击按钮
        $scope.remark_all = function (input_remark) {
            var integral = input_remark;
            var re = /[\+\_\-\~\@\#\$\%\^\&\*\(\)\{\}\:\'\"\<\>\?\[\]]/;
            if (re.test(integral)) {
                baison_app.api.toast({msg: $rootScope.language.MSG_CANT_HAVE_INNOG_STRING}); //'包含非法字符'
                $rootScope.goods_cart.allremark = '';
                return;
            }

            if (typeof input_remark == 'undefined') {
                $rootScope.goods_cart.allremark = '';
            } else {
                $rootScope.goods_cart.allremark = input_remark;
            }

            baison_app.api.toast({msg: $rootScope.language.MSG_SAVE_SUCCESS}); //'保存成功'
            ngDialog.close(windows_remark);
        };
        //整单备注
        $scope.remark_html = function () {
            $scope.more_btns_active = '';
            //测试跳转整单备注
            if ($rootScope.goods_cart.list.length == 0) {
                baison_app.api.toast({msg: $rootScope.language.MSG_NOT_ANY_GOODS}); //'您尚未选择任何商品'
            } else {

                windows_remark = ngDialog.open({closeByDocument: false,
                    template: './html/cashier/all_cashier_remark.html',
                    disableAnimation: true,
                    trapFocus: false,
                    scope: $scope
                });
            }
        };
        //维修业务>>>>>>>>
        $scope.fix_goods_list = [];
        $scope.fix = {};
        $scope.fix.record = {};
        var now_date = new Date();
        var windows = 1;
        //$scope.fix.record.dianyuan=$rootScope.user.UserCode;
        $scope.maintenance = function () {
            $scope.fix.record = {};
            if ($rootScope.goods_cart.list.length <= 0) {
                baison_app.api.toast({msg: $rootScope.language.MSG_NOT_ANY_GOODS}); //'您尚未选择任何商品'
            } else if ($rootScope.goods_cart.vip.vip_code == '') {
                baison_app.api.toast({msg: $rootScope.language.TIPS_SELECT_VIP}); //'请选择会员
            } else {
                windows = ngDialog.open({closeByDocument: false,
                    template: './html/cashier/dialog/fix.html',
                    disableAnimation: true,
                    trapFocus: false,
                    preCloseCallback: function () {
                        $scope.open_windows.pop();
                    },
                    scope: $scope
                });
                $scope.open_windows.push('nothing');
                $scope.fix.record.dianyuan = $rootScope.user.UserCode;
                $scope.fix_goods_list = $rootScope.goods_cart.list;
                $scope.fix.record.customer = $rootScope.goods_cart.vip.customer_name;
                $scope.fix.record.tel = $rootScope.goods_cart.vip.tel;
                $scope.fix.record.customer_code = $rootScope.goods_cart.vip.customer_sn;
                $scope.fix.record.date = now_date;
                $scope.fix.record.remark = '';
                //$scope.fix.record.address='';
                $scope.fix.record.make_person = $rootScope.user.UserName;
                $scope.fix.record.user_code = $rootScope.user.UserCode;
                $scope.fix.record.make_date = now_date;
                $scope.fix.record.receive = 1;
                $scope.fix.record.receive_person = $rootScope.user.UserName;
                $scope.fix.record.receive_date = now_date;
            }
        };
        //$scope.fix.dianyuan=$rootScope.user.UserCode;
        $scope.user = [];
        PosUser.get_user_by_shopCode($rootScope.current_shop.ShopCode).then(function (user) {
            if ($rootScope.user.UserCode == '000') {
                $scope.user.push({
                    UserCode: '000',
                    UserName: $rootScope.language.TIPS_SUPER_ADMINE//超级管理员
                });
            }
            user.forEach(function (data, index) {
                $scope.user.push({UserName: data.UserName, UserCode: data.UserCode})
            });
        });
        //生成维修单
        $scope.pay_fix_money = function () {
            $scope.open_windows.pop();
            //维修单号
            $scope.fix.record.record_code = 'WX' + timeStamp2String(0, 'datetime2') + (Math.random() * 9).toFixed(0) + (Math.random() * 9).toFixed(0);
            $scope.fix.record.shop_code = $rootScope.current_shop.ShopCode;
            $scope.fix.detail = $scope.fix_goods_list;
            $scope.fix.payment = [];
            if (typeof ($scope.fix.record.dianyuan) == 'undefined' || $scope.fix.record.dianyuan == '') {
                baison_app.api.toast({msg: $rootScope.language.TIPS_INPUT_DIANYUAN});
                return;
            }
            if (typeof ($scope.fix.record.customer) == 'undefined' || $scope.fix.record.customer == '') {
                baison_app.api.toast({msg: $rootScope.language.TIPS_INPUT_CUSTOMER});
                return;
            }
            if (typeof ($scope.fix.record.tel) == 'undefined' || $scope.fix.record.tel == '') {
                baison_app.api.toast({msg: $rootScope.language.TIPS_INPUT_TEL});
                return;
            }
            var res = /^(([1-9]\d*)|0)(\.\d{2})?$/;
            if (!res.test($scope.fix.record.fix_money)) {
                baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_INPUT_VALID_AMOUNT});
                return;
            }
            if (typeof ($scope.fix.record.address) == 'undefined' || $scope.fix.record.address == '') {
                baison_app.api.toast({msg: $rootScope.language.TIPS_INPUT_ADDRESS});
                return;
            }
            ngDialog.close(windows);
            //baison_app.api.alert({msg:$scope.fix,title:"fix_record"});
            ServiceOrder.add_fixRecord($scope.fix).then(function (res) {
                if (res.data.status == 1) {
                    baison_app.api.toast({msg: $rootScope.language.TIPS_UPLOAD_FIX_SUCCESS});
                    GoodsCart.clear_cart();
                    $scope.fix = {};
                } else {
                    baison_app.api.toast({msg: $rootScope.language.TIPS_UPLOAD_FIX_FAILED});
                }
                //baison_app.api.alert({msg:res,title:"add_fix_res"});
            });
        };
        $scope.cancel = function () {
            $scope.open_windows.pop();
            ngDialog.close(windows);
        };
        //<<<<<<<<<<<

        //底部按钮区域事件 ========================================================
        $scope.change_specifications = function () {
            if ($rootScope.goods_cart.list.length > 0) {
                // baison_app.api.toast({msg:$rootScope.goods_cart.list[$scope.check_switch].GoodsCode});
                BaseGoods.get_sku_by_code($rootScope.goods_cart.list[$scope.check_switch].GoodsCode).then(function (sku) {
                    // baison_app.api.toast({msg:sku});

                    if (sku.length == 0) {
                        baison_app.api.toast({msg: $rootScope.language.MSG_NOT_FOUND_GOODS}); //没有找到商品
                    }
                    if (sku.length <= $scope.suk_num_max) {
                        $scope.isChangeSpecifications = true;
                        $scope.goods_select_data = sku;
                        $scope.goods_select_data_choose = 0;
                        window_id = ngDialog.open({closeByDocument: false,
                            trapFocus: false,
                            template: './html/component/goods_select.html',
                            disableAnimation: true,
                            scope: $scope,
                            preCloseCallback: function () {
                                $scope.isChangeSpecifications = false;
                                $scope.open_windows.pop();
                            }
                        });
                        $scope.open_windows.push('goods_selector');
                    } else {
                        baison_app.api.toast({msg: $rootScope.language.MSG_GOODS_MORE_INPUT_CODE}); //查到的商品太多，请输入更完整的条码
                    }
                }, function (err) {
                    baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: err});
                });
            } else {
                baison_app.api.toast({msg: $rootScope.language.MSG_NOT_ANY_GOODS});
            }
        }

        //打开钱箱按钮  
        $scope.open_money_box = function () {
            open_money_box();
        };
        //打开钱箱
        var open_money_box = function () {
            var systype = baison_app.api.systemType;
            if (systype == 'ios') {
                var configData = $api.getStorage('configData');
                var pay_type = configData.zftd;
                if (pay_type == 1) { //是盒子支付
                    baison_app.boxPay.openMoneyBox(function (ret, err) {
                        baison_app.api.toast({msg: ret.message});
                    });
                } else {

                }
            } else if (systype == 'android') {
                //飞凡设备
				var configData = $api.getStorage('configData');
                if (configData.feifan.switch == 1) {
                    baison_app.feifanPrint.selectDevice(function () {//开启打印机
                        baison_app.feifanPrint.openBox(function (ret, err) {
                            baison_app.feifanPrint.closeDevice(function (ret, err) {//关闭打印机
                            });
                        });
                    });
                }
            }


        };
        //应付零价商品自动加入结算记录（现金收银）
        var auto_add_zero_goods = function () {
            if ($rootScope.goods_cart.info.need_money <= 0) {
                //添加数据
                GoodsCart.add_check('001', $rootScope.language.TIPS_CASHIER_CASH_MONEY, 0, 0, '', '');
            }
        };
        //去结算
        $scope.go_settle = function () {

            if ($scope.jumpAble == 0) {
                baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_SYS_BUSY_LODING})//'系统繁忙，请稍后'
                return;
            }
			if ($rootScope.goods_cart.g_giftnum != $rootScope.goods_cart.g_giftednum) {
                baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: "赠品未加载完成"})//'系统繁忙，请稍后'
                return;
			}else{
				$rootScope.goods_cart.g_giftnum = 0;
				$rootScope.goods_cart.g_giftednum = 0;
			}
            if ($rootScope.goods_cart.giftnum != $rootScope.goods_cart.giftednum) {
                baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: "赠品未加载完成"})//'系统繁忙，请稍后'
                return;
            }else{
                $rootScope.goods_cart.giftnum = 0;
                $rootScope.goods_cart.giftednum = 0;
            }


            if ($rootScope.goods_cart.list.length == 0) {
                baison_app.api.toast({msg: $rootScope.language.MSG_NOT_ANY_GOODS}); //'您尚未选择任何商品'
            } else {
                //根据购物车内容生成未结算的小票
                $rootScope.goods_cart.list.forEach(function (n) {
                    if (n.daogou == '') {
                        n.daogou = $rootScope.user.UserCode;
                    }
                });
                auto_add_zero_goods();
////              //根据优惠券信息，在结算列表显示优惠券信息
//              if(Object.keys($rootScope.goods_cart.couponData).length > 0){
//              	$.each($rootScope.goods_cart.couponData,function(i,n){
//              	    //未绑定促销的
//              	     if(n.coupon.type == 1){
//           	 	 	 	   var money = $rootScope.goods_cart.info.total_money-($rootScope.goods_cart.info.total_money)*n.coupon.rebate;
//           	 	 	 	   var final_money=(money > $rootScope.goods_cart.info.total_money) ? $rootScope.goods_cart.info.total_money : money;
//           	 	 	 	   final_money = parseFloat(final_money);
//           	 	 	 	   money = parseFloat(money);
//           	 	 	 	   var coupon_code = n.detail.coupon_code;
//           	 	 	 	   var  remark = '优惠券：' + coupon_code + '；面额：' + money;
//           	 	 	 	   GoodsCart.add_check('003', '优惠券', money, final_money, coupon_code, remark);
//              	       }
//              	      if(n.coupon.type == 3){
//           	 	 	 	   var money = n.detail.money;
//           	 	 	 	   var final_money = (money > $rootScope.goods_cart.info.total_money) ? $rootScope.goods_cart.info.total_money : money;
//                              final_money = parseFloat(final_money);
//           	 	 	 	   var coupon_code = n.detail.coupon_code;
//           	 	 	 	   var  remark = '优惠券：' + coupon_code + '；面额：' + money;
//           	 	 	 	   GoodsCart.add_check('003', '优惠券', money, final_money, coupon_code, remark);
//              	      } 
//              	     //绑定促销
//              	});
//              }


                ReceiptRecord.add($rootScope.goods_cart).then(function (response) {

                    //console.log(JSON.stringify(response));
                    if (response.data.status == 1 || response.data.status == '1') {
                        baison_app.api.toast({msg: $rootScope.language.MSG_RECEIPT_SAVE_SUCCESS}); //'小票保存成功'
                    } else {
                        baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_RECEIPT_SAVE_DEFEAT + $rootScope.language[response.data.code]}); //'小票保存失败：'
                    }
                }).catch(function (err) {
                    baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_RECEIPT_SAVE_ERROR + err}); //'小票保存错误：' 
                });
                $location.path('/cashier/settle');
            }
        };
        //挂单 将购物车商品信息保存至挂单数组，然后清空购物车
        $scope.hold_receipt = function () {

            $scope.more_btns_active = '';

            if ($rootScope.hold_receipt_data.length >= 6) {
                baison_app.api.toast({msg: $rootScope.language.TIPS_CASHIER_HOLD_NO_MORE_SIX}); //'最多挂六单'
                return;
            }

            if ($rootScope.goods_cart.list.length == 0) {
                baison_app.api.toast({msg: $rootScope.language.MSG_WITHOUT_SELECT_GOODS}); //'未选择商品'
                return;
            }
            //有促销商品不可挂单
            var has_promotion = false;
            $.each($rootScope.goods_cart.current_promotions, function (i, n) {
                has_promotion = n.isUse;

            });
            if (has_promotion) {
                baison_app.api.toast({msg: $rootScope.language.TIPS_CASHIER_HOLD_NO_PROMOTION}); //'促销商品不允许挂单'
                return;
            }

            //有优惠券不可挂单
            var has_coupon = false;
            $.each($rootScope.goods_cart.couponData, function (i, n) {
                if (n != undefined) {
                    has_coupon = true;

                }
            });
            if (has_coupon) {
                baison_app.api.toast({msg: $rootScope.language.TIPS_CASHIER_HOLD_NO_USECOUPON}); //'使用优惠券不允许挂单'
                return;
            }
            $rootScope.goods_cart.checklist.forEach(function (n) {
                if (n.code == '003') {
                    has_coupon = true;
                }
            });
            if (has_coupon) {
                baison_app.api.toast({msg: $rootScope.language.TIPS_CASHIER_HOLD_NO_USECOUPON}); //'使用优惠券不允许挂单'
                return;
            }
            if ($rootScope.goods_cart.list.length == 0) {
                baison_app.api.toast({msg: $rootScope.language.MSG_WITHOUT_SELECT_GOODS}); //'未选择商品'
                return;
            }
            $rootScope.hold_receipt_data.unshift({
                time: new Date(),
                list: $rootScope.goods_cart.list,
                allremark: $rootScope.goods_cart.allremark,
                vip: $rootScope.goods_cart.vip.vip_code
            });
            GoodsCart.clear_cart();
            //最大挂单6条数据
            if ($rootScope.hold_receipt_data.length > 6) {
                $rootScope.hold_receipt_data.pop();
            }
            baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_GUADAN_SUCCESS}); //'挂单成功！'
        };
        //取单
        $scope.get_receipt_index = 0;
        $scope.get_receipt = function (index) {
            $scope.get_receipt_index = index;
            if ($rootScope.hold_receipt_data[index] == undefined) {
                baison_app.api.toast({'msg': '该笔挂单不存在！Ctrl+1 ~ Ctrl+6分别对应各张挂单'});
                return;
            }
            $scope.get_receipt_data = $rootScope.hold_receipt_data[index];
            $scope.get_receipt_index = index;
            window_id = ngDialog.open({closeByDocument: false,
                trapFocus: false,
                template: './html/cashier/get_receipt.html',
                disableAnimation: true,
                scope: $scope,
                preCloseCallback: function () {
                    $scope.open_windows.pop();
                }
            });
            $scope.open_windows.push('hold_receipt');
        };
        $scope.get_receipt_confirm = function (index) {
            GoodsCart.clear_cart();
            VIP.vip_search({vip_code: $rootScope.hold_receipt_data[index].vip}).then(function (response) {
                if (response.data.status == 1) {
                    var data = response.data.data;
                    GoodsCart.set_current_vip(data);
                } else {
                    $rootScope.goods_cart.vip = {};
                }
            });
            GoodsCart.add_to_cart_batch($rootScope.hold_receipt_data[index].list);
            $rootScope.goods_cart.allremark = $rootScope.hold_receipt_data[index].allremark;
            $rootScope.hold_receipt_data.splice(index, 1);
            ngDialog.close(window_id);
        };
        //抹零功能
        $scope.cut_money = function () {
            $scope.more_btns_active = '';
            if ($rootScope.goods_cart.list.length == 0) {
                baison_app.api.toast({msg: $rootScope.language.MSG_WITHOUT_SELECT_GOODS});
                return;
            }
            GoodsCart.cut_money();
        };
        //退货功能
        $scope.return_receipt = function () {
            //判断是否有权限
            if ($rootScope.purview['\/CashierReturnCtrl\/return_receipt'].show == 0) {
                return;
            }
            $location.path('/cashier/return/null');
        };
        //新建顾客
//      $scope.add_customer = function () {
//          $scope.more_btns_active = '';
//          //默认属性
//          $scope.customer = {
//              'tel': '',
//              'name': '',
//              'birthday': '',
//              'sex': '1'
//          };
//          window_id = ngDialog.open({closeByDocument: false,
//              trapFocus: false,
//              template: './html/cashier/dialog/add_customer.html',
//              disableAnimation: true,
//              scope: $scope
//          });
//          $scope.add_customer_enable = true;
//      };
        //储值卡挂失
        $scope.card_loss = function () {
            $scope.czkData = {};
            //判断是否是已经输入会员 ，若没有选择会员
            $scope.czkData.name = '';
            $scope.czkData.tel = '';
            $scope.czkData.czkCode = '';
            $scope.czkData.password = '';
            $scope.czkData.money = '';
            window_id = ngDialog.open({closeByDocument: false,
                trapFocus: false,
                template: './html/cashier/dialog/card_loss.html',
                disableAnimation: true,
                scope: $scope,
                controller: ['$scope', '$rootScope', function ($scope, $rootScope) {
                        var current_vip = $rootScope.goods_cart.vip;
                        //若当前会员不为空
                        if (current_vip.vip_code != '') {
                            //current_vip：姓名和手机号
                            $scope.czkData.tel = current_vip.tel;
                            $scope.czkData.name = current_vip.customer_name;
                            //根据tel获取储值卡信息,可能是一人多卡
                            Cards.getCards_by_code(current_vip.tel).then(function (response) {
                                if (response.data.status == 1) {
                                    $scope.czkCardsGroup = response.data.data;
                                }
                            });
                        }
                        //储值卡挂失：根据储值卡查找信息
                        $scope.check_czk = function (password, code) {
                            var re = /^[0-9]+[0-9]*$/;
                            if (!re.test(code)) {
                                baison_app.api.toast({msg: $rootScope.language.MSG_PLI_INPUT_SAVING_CARD_CODE_USE}); //'请输入一个有效的储值卡卡号'
                                $scope.czkData.czkCode = '';
                                return;
                            }
                            //输入储值卡号         
                            if (code == '') {
                                baison_app.api.toast({msg: $rootScope.language.MSG_PLI_INPUT_SAVING_CARD_CODE}); //'请输入储值卡号'
                                return;
                            } else {
                                //根据储值卡号和密码自动获取储值卡信息
                                Cards.cardsNo_search(code, password).then(function (response) {
                                    if (response.data.status == 1) {
                                        $scope.czkData.name = response.data.data.mc; //名称
                                        $scope.czkData.tel = response.data.data.sj; //手机
                                        $scope.czkData.money = response.data.data.dqje; //当前余额
                                    } else {
                                        baison_app.api.toast({msg: $rootScope.language.MSG_CANT_FOUND_RESULT}); //'没有查询到结果'
                                    }
                                });
                            }
                        };
                    }]
            });
        };
        //缺货登记
        $scope.lack_register = function () {
            $scope.lackData = {};
            //经手店员名称、经手店员代码、日期、顾客姓名、手机号、订金金额、联系地址、商品、备注
            $scope.lackData.UserName = '';
            $scope.lackData.UserCode = '';
            $scope.lackData.date = new Date();
            $scope.lackData.customerName = '';
            $scope.lackData.tel = '';
            $scope.lackData.deposit = '';
            $scope.lackData.address = '';
            $scope.lackData.goods = [];
            $scope.lackData.remark = '';
            $scope.lackData.customer_code = ''; //顾客代码
            //判断购物车是否为空
            if ($rootScope.goods_cart.list.length <= 0) {
                baison_app.api.toast({msg: $rootScope.language.TIPS_SELECT_GOODS});//请先选择商品
                return;
            }
            //若当前会员已经存在
            var current_vip = $rootScope.goods_cart.vip;
            if (current_vip.vip_code == '') {
                baison_app.api.toast({msg: $rootScope.language.TIPS_LACK_REGISTER_NO_MEMBER});//当前不是会员，无法进行商品预定
                return;
            }

            window_id = ngDialog.open({closeByDocument: false,
                trapFocus: false,
                template: './html/cashier/dialog/lack_register.html',
                disableAnimation: true,
                scope: $scope,
                controller: ['$scope', '$rootScope', 'PosUser', function ($scope, $rootScope, PosUser) {

                        $scope.lackData.tel = current_vip.tel;
                        $scope.lackData.customerName = current_vip.customer_name;
                        $scope.lackData.customer_code = current_vip.customer_sn; //顾客代码
                        //获取当前店铺的收银员
                        var shop_code = $rootScope.current_shop.ShopCode;
                        PosUser.get_user_by_shopCode(shop_code).then(function (response) {
                            $.each(response, function (i, n) {
                                response[i].UserInfo = n.UserName + '_' + n.UserCode;
                            });
                            $scope.users = response;
                            $scope.lackData.UserName = response[0].UserInfo; //在界面显示名称 name下拉框对应 代码（系统管理员：000）
                        });
                        //遍历购物车商品
                        $.each($rootScope.goods_cart.list, function (i, n) {
                            $scope.lackData.goods.push(n);
                        });
                    }]
            });
        };
        //外卡
        $scope.Wildcard = function () {
            $scope.wildCard = '';
            $scope.rebate = '';
            window_id = ngDialog.open({closeByDocument: false,
                trapFocus: false,
                template: './html/cashier/dialog/wild_card.html',
                disableAnimation: true,
                scope: $scope,
                controller: ['$scope', '$rootScope', 'Cards', function ($scope, $rootScope, Cards) {
                        $scope.select_wildCard = function (card) {
                            //根据外卡卡号获取折扣
                            Cards.get_rebate_by_wildCard(card).then(function (response) {
                                if (response.data.status == 1) {
                                    if (response.data.data.data.length == 0) {
                                        baison_app.api.toast({msg: $rootScope.language.TIPS_CASHIER_USE_WILDERCARD_OR_NOT});
                                        return;
                                    }
                                    //查到外卡信息
                                    if (response.data.data.data.length > 0) {
                                        $scope.rebate = response.data.data.data[0].zk; //折扣
                                        $rootScope.yxdjsy = response.data.data.data[0].yxdjsy; //是否允许叠加使用
                                        $rootScope.zk = $scope.rebate;
                                    }
                                }
                            });
                        };
                    }]
            });
        };
        //促销
        $scope.sales_prom = function () {

            Promotion.get_available_promotion().then(function (success) {

                var _current_promotions = [];
                $.each($rootScope.goods_cart.current_promotions, function (i, n) {
                    _current_promotions.push(n.promotion_rule_id);
                });
                var _available_promotions = {};
                $.each($rootScope.goods_cart.available_promotions, function (i, n) {
                    if ($.inArray(n.promotion_rule_id, _current_promotions) >= 0) {
                        n.selected = true;
                    }
                    if ($rootScope.goods_cart.available_promotions[i].promotion_type != 5) {
                        _available_promotions[i] = n;
                    }

                });
                window_id = ngDialog.open({closeByDocument: false,
                    template: './html/cashier/dialog/sales_prom.html',
                    disableAnimation: true,
                    scope: $scope,
                    trapFocus: false,
                    controller: ['$scope', function ($scope) {
                            $scope.available_promotions = _available_promotions;
                        }],
                    preCloseCallback: function () {
                        $scope.open_windows.pop();
                    }
                });
                $scope.open_windows.push('sales_prom');
            });
        };
        //跳到促销列表
        $scope.promotion_index = function () {
            ngDialog.close(window_id);
            $location.path('/promotion/index');
        };
        //获取赠送物品
        var get_gift_goods = function (detail) {
            var pid = detail.promotion_rule_id;
            //赠送数量
            var num = detail.gift_total_num; //赠品所在促销的详情
            $scope.gift_detail = detail;
            //所有赠品信息
            $scope.gift_goods = [];
            //选中赠品列表
            $scope.gift_list = [];
            //选中赠品数量列表
            $scope.gift = [];
            //赠送数量
            $scope.giftnum = num;
            Promotion.get_gift_goods(pid).then(function (ret) {
                //console.log(pid);
                //console.log(JSON.stringify(ret));
                //赠品数量
                var giftnum = ret.length;
                if (giftnum != 0) {
                    // if (giftnum <= num) {
                    //     //console.log(JSON.stringify(ret));
                    //     detail.gift_list = ret;
                    //     GoodsCart.add_current_promotion(detail);
                    // } else if (giftnum > num) {
                    gift_id = ngDialog.open({closeByDocument: false,
                        template: './html/cashier/dialog/gift_prom.html',
                        disableAnimation: true,
                        scope: $scope,
                        controller: ['$scope', function ($scope) {
                                $scope.gift_goods.gift_list = ret;
                                $scope.gift_goods.gift_list.forEach(function (n, i) {
                                    $scope.gift[i] = 0;
                                });
                            }]
                    });
                    //}
                }

            });
        };
        //选择赠品数组
        var gift_list = [];
        //添加赠送物品
        $scope.giftgoods_add = function (gift, index) {
            if ($scope.giftnum <= 0) {
                baison_app.api.toast({msg: $rootScope.language.MSG_CANT_SELECT_OTHER_GOODS}); //'不能再选择其他商品'
                return;
            }
            $scope.giftnum = $scope.giftnum - 1;
            $scope.gift_list.push(gift);
            $scope.gift[index] += 1;
        };
        //删除赠送物品
        $scope.giftgoods_del = function (gift, index) {
            if ($scope.gift[index] <= 0) {
                return;
            }
            $scope.giftnum = $scope.giftnum + 1;
            var n = {};
            for (var i = 0; i < $scope.gift_list.length; i++) {
                n = $scope.gift_list[i];
                if (n.sku == gift.sku) {
                    $scope.gift_list.splice(i, 1);
                    break;
                }
            }
            $scope.gift[index] -= 1;

        };

        //确定赠品
        $scope.confirm_gift = function () {
            var goods_status = 1;
            $scope.gift_detail.gift_list = $scope.gift_list;
            $rootScope.goods_cart.giftnum = $rootScope.goods_cart.giftnum*1 + $scope.gift_list.length*1;
            $scope.gift_detail.goods_status = goods_status;
            GoodsCart.add_current_promotion($scope.gift_detail);
            ngDialog.close(gift_id);
            $scope.gift_detail = {};
        };
        //从可用促销里面选择应用促销
        $scope.sales_prom_on_change = function (detail) {
            if ($rootScope.goods_cart.list.length == 0) {
                return;
            }
            if (detail.selected === true) {
                //选择促销内已有独享的，不能重复选择独享
                if (detail.is_share == 1 && $rootScope.goods_cart.share_promotion_id != 0 && $rootScope.goods_cart.share_promotion_id != detail.promotion_rule_id) {
                    detail.selected = false;
                    return;
                }
                if (!GoodsCart.is_check_apply_promotion(detail)) {

                    return;
                }

                if (detail.promotion_type == 1 || detail.promotion_type == 3) {//满额赠件
                    get_gift_goods(detail);
                } else {
                    GoodsCart.add_current_promotion(detail);
                }
            } else {
                GoodsCart.del_current_promotion(detail);
            }
        };
        //套组
        //套组初始化
        var group_init = function () {
            $scope.group = {step: 1};
            $scope.group_mid_list = [];
            $rootScope.goods_cart.promotion_group_mid_list = {};
            $rootScope.goods_cart.promotion_group_list = {};
            $rootScope.goods_cart.mid_goods = [];
            $scope.skus = {};
            $scope.group_prom_rule_id = '';
        };
        group_init();
        //选择套组

        $scope.sleeve_group = function () {
            group_init();
            var _input_keyword = $scope.input_keyword;
            BaseGoods.get_sku_by_code(_input_keyword).then(function (sku) {

                if (sku.length == 0) {
                    baison_app.api.toast({msg: $rootScope.language.MSG_WITHOUT_FOUND_GOODS}); //'没有找到商品'
                    return;
                } else if (sku.length > 1) {
                    baison_app.api.toast({msg: $rootScope.language.MSG_GOODS_MANY_INPUT_MORE_CODE}); //'查到的商品太多，请输入更完整的条码'
                    return;
                }

                //只有一条记录的时候
                GoodsCart.get_sleeve_group_step_1(sku[0]).then(function (ret) {

                    if (Object.keys($rootScope.goods_cart.promotion_group_list).length <= 0) {
                        baison_app.api.toast({msg: $rootScope.language.MSG_WITHOUT_COMBO_USE}); //'无对应套餐可用!'
                        return;
                    }

                    window_id = ngDialog.open({closeByDocument: false,
                        template: './html/cashier/dialog/sleeve_group.html',
                        disableAnimation: true,
                        scope: $scope,
                        trapFocus: false,
                        controller: ['$scope', function ($scope) {
                                $scope.promotion_group_list = $rootScope.goods_cart.promotion_group_list;
                                $scope.skus = {};
                            }]
                    });
                });
            }, function (err) {
                baison_app.api.toast({msg: err});
            });
        };
        //判断是否可以使用套组（优惠券的判定）
        var check_group_promotion_by_coupon = function (group_info) {

            var use = false;
            if (group_info.is_coupon == 0) {
                use = true;
                return use;
            }
            if (group_info.is_coupon == 1 && $rootScope.goods_cart.couponData[group_info.promotion_rule_id] == undefined) {
                baison_app.api.toast({msg: $rootScope.language.TIP_GOODS_COUPON});
                return use;
            }
            var n = {};
            for (var i = 0; i < $rootScope.goods_cart.couponData[group_info.promotion_rule_id].coupon.coupon_code.length; i++) {
                n = $rootScope.goods_cart.couponData[group_info.promotion_rule_id].coupon.coupon_code[i];
                if (!n.is_use) {
                    use = true;
                    break;
                }
            }
            if (!use) {
                baison_app.api.toast({msg: $rootScope.language.TIP_GOODS_COUPON});
            }
            return use;
        };
        //选择套组到组别界面
        $scope.choose_group_step = function (group_info) {
            if (!check_group_promotion_by_coupon(group_info)) {
                return;
            }
            $scope.group_prom_rule_id = group_info.promotion_rule_id;
            GoodsCart.get_sleeve_group_step_2(group_info).then(function () {
                var merge_mid_list = {};
                if ($rootScope.goods_cart.mid_goods.length == 1) {
                    var mid = $rootScope.goods_cart.mid_goods[0].mid;
                    $rootScope.goods_cart.promotion_group_mid_list[mid] = {};
                    delete $rootScope.goods_cart.promotion_group_mid_list[mid];
                } else if ($rootScope.goods_cart.mid_goods.length > 1) {
                    //合并商品
                    merge_mid_list = [];
                    $.each($rootScope.goods_cart.mid_goods, function (k, v) {
                        $rootScope.goods_cart.promotion_group_mid_list[v.mid][v.index] = {};
                        delete $rootScope.goods_cart.promotion_group_mid_list[v.mid][v.index];
                        $.each($rootScope.goods_cart.promotion_group_mid_list, function (key, value) {
                            if (v.mid == key) {
                                $.each(value, function (i, n) {
                                    if (i != v.index) {
                                        merge_mid_list.push(n);
                                    }
                                });
                            }
                        });
                        $rootScope.goods_cart.promotion_group_mid_list[v.mid] = {};
                        delete $rootScope.goods_cart.promotion_group_mid_list[v.mid];
                    });
                    $rootScope.goods_cart.promotion_group_mid_list.merge = merge_mid_list;
                }

                $scope.goods_name = $rootScope.goods_cart.promotion_group_input_sku.GoodsName;
                $scope.group_mid_list = $rootScope.goods_cart.promotion_group_mid_list;
                $scope.group.step = 2;
                $rootScope.goods_cart.mid_goods = [];
            });
        };
        //取消套餐
        $scope.cancel_group_step = function () {
            var selsku = $rootScope.goods_cart.promotion_group_input_sku.detail[0];
            BaseGoods.get_sku_by_code(selsku.sku).then(function (sku) {
                $scope.goods_select_click(sku[0]);
            });
        };
        //返回选择套组
        $scope.return_group_step = function () {
            $scope.group.step = 1;
            $rootScope.goods_cart.promotion_group_mid_list = {};
            $scope.group_mid_list = [];
        };
        //确认套餐
        $scope.apply_group = function (skus) {
            if ($scope.group.step == 1) {
                baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_SELECT_PACKAGE_ITEMS}); //'请选择套餐物品'
                return;
            }
            var is_empty = 0;
            var num = 0;
            var len = 0;
            for (var key in skus) {
                is_empty = 1;
                num++;
            }
            for (var k in $scope.group_mid_list) {
                len++;
            }
            if (is_empty == 0) {
                baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_SELECT_PACKAGE_ITEMS}); //'请选择套餐物品'
                return;
            }
            if (len > num) {
                baison_app.api.toast({msg: $rootScope.language.MSG_MISS_PACKAGE_ITEMS});
                return;
            }
            var datetime = new Date();
            var goods_status = parseInt(datetime.getTime() / 1000);

            var selsku = {};
            for (var j = 0; j < $rootScope.goods_cart.promotion_group_input_sku.detail.length; j++) {
                if ($rootScope.goods_cart.promotion_group_input_sku.detail[j].promotion_rule_id == $scope.group_prom_rule_id) {
                    selsku = $rootScope.goods_cart.promotion_group_input_sku.detail[j];
                    break;
                }
            }
			$rootScope.goods_cart.g_giftnum += (len+1)*1;
            BaseGoods.get_sku_by_code(selsku.sku).then(function (sku) {
                if (sku[0] != undefined) {
					
                    //console.log(skus);
                    skus[num]={
                        sku:sku[0].SkuCode,
                        price:selsku.price,
                        num:sku[0].num
                    };
					ngDialog.close(window_id);
                    //GoodsCart.add_gift_to_cart(sku[0], $scope.group_prom_rule_id, 5, selsku.price, goods_status);
                    //与促销对接
                    Promotion.get_available_promotion().then(function (success) {
                        //console.log(success);
                        //$.each($rootScope.goods_cart.available_promotions, function (pro_id, detail) {
                            // TODO 套组促销ID
                            
                            if ($rootScope.goods_cart.available_promotions[$scope.group_prom_rule_id] != undefined) {
                                //console.log(detail);
                                detail = $rootScope.goods_cart.available_promotions[$scope.group_prom_rule_id];
                                //console.log($rootScope.goods_cart.available_promotions);
								
                                GoodsCart.add_gift_to_cartlist(skus, $scope.group_prom_rule_id, 5,goods_status);
                                detail.group_goods = skus;
                                detail.goods_status = goods_status;
                                detail.used_num = 1;
                                detail.can_used_num = 1;
                                detail.isUse = true;
                                $rootScope.goods_cart.current_promotions[detail.promotion_rule_id] = detail;
                                
                            }
                        //});
                        // GoodsCart.add_gift_to_cart(sku[0], $scope.group_prom_rule_id, 5, selsku.price, goods_status).then(function () {
                        //     Promotion.get_available_promotion().then(function (success) {
                        //         GoodsCart.refresh_cart_to_promotion();
                        //     });
                        // });

                        $scope.group.step = 1;
                        //ngDialog.close(window_id);
                        $scope.input_keyword = '';
                        $scope.group_prom_rule_id = '';
                    });
                }
            });
        };
        //弹框处理================================================================
        //保存顾客
        $scope.saveCustomer = function (customer) {
            //不能重复提交
            if (!$scope.add_customer_enable) {
                return;
            }
            if (customer.tel == undefined || customer.tel == '') {
                baison_app.api.toast({msg: $rootScope.language.MSG_PHONE_NUM_VALIDATION_FAILS}); //'手机号码验证失败'
                return;
            }
            if (customer.name == undefined || customer.name == '') {
                baison_app.api.toast({msg: $rootScope.language.MSG_NAME_IS_CANT_EMTY}); //'姓名不能为空'
                return;
            }
            if (customer.birthday == undefined || customer.birthday == '') {
                baison_app.api.toast({msg: $rootScope.language.MSG_BIRTHDAY_IS_CANT_EMTY}); //'生日不能为空'
                return;
            }
            $scope.add_customer_enable = false;
            VIP.add_customer(customer).then(function (response) {
                $scope.add_customer_enable = true;
                if (response.data.status == 1) {
                    baison_app.api.toast({msg: $rootScope.language[response.data.message]});
                    ngDialog.close(window_id);
                } else {
                    baison_app.api.toast({msg: $rootScope.language.MSG_NEW_CUSTOMER_ADD_FAILS}); //'顾客新增失败'
                }
            });
        };
        //重置顾客
        $scope.clearCustomer = function () {
            $scope.customer = {
                'tel': '',
                'name': '',
                'birthday': '',
                'sex': '1'
            };
        };
        //储值卡挂失
        $scope.cardLoss = function (czkData) {
            //储值卡挂失接口
            Cards.prepaidCard(czkData).then(function (response) {
                if (response.data.status == 1) {
                    baison_app.api.toast({msg: response.data.message});
                } else {
                    baison_app.api.toast({msg: $rootScope.language.MSG_REPORT_LOSS_FAIL}); //'挂失失败'
                }
            });
        };
        //关闭储值卡挂失弹框
        $scope.cardwindow_close = function () {
            ngDialog.close(window_id);
        }

        //缺货登记提交
        $scope.lackRegisterSubmit = function (lackData) {
            if (lackData.UserName == '') {
                baison_app.api.toast({msg: $rootScope.language.TIP_SELECT_USER_CODE});
                return;
            }
            if (lackData.date == '') {
                baison_app.api.toast({msg: $rootScope.language.TIP_SELECT_DATE});
                return;
            }
            if (lackData.deposit == '') {
                baison_app.api.toast({msg: $rootScope.language.TIP_FILL_PAY_MONEY});
                return;
            }
            var userinfo = lackData.UserName.split('_');
            lackData.UserCode = userinfo[1];     //经手店员代码
            //全局变量存储顾客订金单的经手店员
            $rootScope.gkdjd_userCode = userinfo[1];
            lackData.is_made_person = $rootScope.user.UserName; //制单人：当前登录人
            lackData.is_sure_person = $rootScope.user.UserName; //确认人：当前登录人
            lackData.date = timeStamp2String(lackData.date, 'datetime');
            LackRegister.addDepositRecord(lackData).then(function (response) {
                if (response.data.status == 1) {
                    baison_app.api.toast({msg: response.data.message});
                    ngDialog.close(window_id);
                } else {
                    baison_app.api.toast({msg: response.data.message});
                }
            });
        };
        //关闭缺货登记弹框
        $scope.lack_window_close = function () {
            ngDialog.close(window_id);
        };
        //确认使用外卡
        $scope.use_wildCard = function (rebate) {
            //判断是否录入会员
            var current_vip = $rootScope.goods_cart.vip;
            if (current_vip.vip_code != '') {
                //1表示允许叠加使用  0表示不允许
                //若不勾选就提示：该外卡不能与vip卡同时使用
                if ($rootScope.yxdjsy == "0") {
                    baison_app.api.toast({msg: $rootScope.language.TIPS_CASHIER_USE_WILDERCARD});
                    return;
                }
                //判断当前是否已输入VIP卡号，如已输入，则判断当前外卡是否勾选"允许与VIP叠加使用"
                if ($rootScope.yxdjsy == "1") {
                    //(如果有会员)折扣等于两个折扣相乘,刷新购物车
                    GoodsCart.refresh_cart_num();
                }
            } else {
                //若没有录入vip,就取折扣，
                //折扣等于外卡折扣
                GoodsCart.refresh_cart_num();
            }
            ngDialog.close(window_id);
        };
        //商品选择器
        $scope.goods_select_click = function (sku) {
            if ($scope.isChangeSpecifications)
            {
                GoodsCart.change_specifications_in_cart($scope.check_switch, sku);
                ngDialog.close(window_id);
                return;
            }


            if (sku.SkuNum <= 0) {
                sku.flag = 1;
            }
            if ($rootScope.user.UserCode == '000') {
                //临时修改，如果用户为000 先不管导购员
//                GoodsCart.add_to_cart(sku, $scope.configData.daogou, '000');
                GoodsCart.add_to_cart(sku, $scope.configData.daogou, $scope.memberGuide[0].UserCode);
            } else {
                GoodsCart.add_to_cart(sku, $scope.configData.daogou, $rootScope.user.UserCode);
            }

//          GoodsCart.add_to_cart(sku);
            $scope.input_keyword = '';
            $scope.selector = 'sku';
            $scope.selector_class = 'sku';
            ngDialog.close(window_id);
        };
        //会员选择器
        $scope.vip_select_click = function (vip) {
            GoodsCart.set_current_vip(vip);
            //会员输入成功后自动切换回商品
            $scope.selector = 'sku';
            ngDialog.close(window_id);
        };
        //更换导购员
        $scope.change_daogou = function (daogou_code, index) {
            if ($scope.configData.daogou == 0) {
                //更新购物车内全部SKU的导购员代码, 单导购的情况
                GoodsCart.change_daogou_all(daogou_code);
            } else {
                $rootScope.goods_cart.list[index].daogou = daogou_code;
            }
        };
//关闭系统键盘
        $scope.inputClose = function () {
            //判断是否有权限操作系统键盘
            if ($rootScope.purview['\/change_keyBoard'].show == 0) {
                return;
            }
            var setKeyboard = document.getElementById("inputDesk");
            setKeyboard.setAttribute("readOnly", 'true');
        };
//打开和关闭系统键盘
        var inputTest = 0;
        $scope.inputOpen = function () {
            //判断是否有权限操作系统键盘
            if ($rootScope.purview['\/change_keyBoard'].show == 0) {
                return;
            }
            inputTest = !inputTest;
            if (inputTest) {
                var setKeyboard = document.getElementById("inputDesk");
                setKeyboard.removeAttribute("readOnly");
                setKeyboard.focus();
                //$scope.selector = 'keyboardOpen';
                //打开的时候不提示，关闭才提示
                //baison_app.api.toast({msg: $rootScope.language.MSG_KEYBOARD_OPEN});
            } else {
                $scope.inputClose();
                //$scope.selector = 'keyboardClose';
                baison_app.api.toast({msg: $rootScope.language.MSG_KEYBOARD_CLOSE});
            }
            if ($scope.animat_p == "") {
                $scope.animat_p = "rotateX";
            } else {
                $scope.animat_p = "";
            }
        };
        //PC版本默认打开系统键盘
        $timeout(function () {
            if (isPC) {
                inputTest = 0;
                $scope.inputOpen();
            }
        }, 500);
        //整单改导购
        $scope.receiptGuide = function () {
            if ($rootScope.goods_cart.list.length <= 0) {
                baison_app.api.toast({msg: $rootScope.language.MSG_NOT_ANY_GOODS}); //'您尚未选择任何商品'
                return;
            }
            receipt_guide = ngDialog.open({closeByDocument: false,
                trapFocus: false,
                template: './html/cashier/keypad/receipt_change_guide.html',
                disableAnimation: true,
                scope: $scope,
                preCloseCallback: function () {
                    $scope.open_windows.pop();
                },
                controller: ['$scope', function ($scope) {
                        //获取导购
                        $scope.returnData = {};
                        $scope.returnData.pay_type = 0;
                        $scope.guide_select = $scope.memberGuide[0].UserCode;
                    }]
            });
            $scope.open_windows.push('nothing');
        };
        //确认改导购
        $scope.confirmGuide = function (ret) {
            $scope.open_windows.pop();
            $rootScope.goods_cart.list.forEach(function (n) {
                n.daogou = ret;
                ngDialog.close(receipt_guide);
            });
        };
        //取消改导购
        $scope.cancelGuide = function () {
            $scope.open_windows.pop();
            ngDialog.close(receipt_guide);
        };
        //获取输入配置
        var configData = $api.getStorage('configData');
        if (configData.keyboard == 0) {
            $scope.inputClose();
        }
        var return_reason = [];
        //无票退
        $scope.no_ticket_return = function () {
            $scope.more_btns_active = ''
            if ($scope.configData.no_ticket_return == 0) {
                baison_app.api.toast({msg: $rootScope.language.MSG_TEMPORARY_UNDEVELOPED_STAY_TUNED}); //'暂未开发，敬请期待..'
                return;
            }
            if ($scope.jumpAble == 0) {
                baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_SYS_BUSY_LODING})//'系统繁忙，请稍后'
                return;
            }

            if ($rootScope.goods_cart.list.length == 0) {
                baison_app.api.toast({msg: $rootScope.language.MSG_NOT_ANY_GOODS}); //'您尚未选择任何商品'
            } else {
                //弹出选择退款方式及原因对画框
                no_return_window = ngDialog.open({closeByDocument: false,
                    trapFocus: false,
                    template: './html/cashier/dialog/no_ticket_return.html',
                    disableAnimation: true,
                    scope: $scope,
                    preCloseCallback: function () {
                        $scope.open_windows.pop();
                    },
                    controller: ['$scope', '$rootScope', function ($scope, $rootScope) {
                            //获取退货原因
                            $scope.returnData = {};
                            $scope.returnData.pay_type = 0;
                            BaseGoods.returnReason().then(function (ret) {
                                if (ret[0] != undefined) {
                                    $scope.returnData.trade_type_name = ret[0].trade_type_code;
                                    $scope.return_reason = return_reason = ret;
                                }
                                //console.log($rootScope.goods_cart.info);
                                $scope.return_money = $rootScope.goods_cart.info.need_money;
                            });
                        }]
                });
                $scope.open_windows.push('nothing');
            }

        };
        //取消无票退货按钮
        $scope.no_ticket_window_close = function () {
            $scope.open_windows.pop();
            ngDialog.close(no_return_window);
        };
        //确认无票退货按钮功能
        $scope.no_ticket_confirm_return = function (returnData) {
            $.each(return_reason, function (i, v) {
                if (v.trade_type_code == returnData.trade_type_name) {
                    $rootScope.goods_cart.reason = v.trade_type_name;
                }
            });
            if (returnData.pay_type == 0) {
                $rootScope.goods_cart.trade_type_code = '001';
            } else if (returnData.pay_type == 1) {
                $rootScope.goods_cart.trade_type_code = '002';
            } else if (returnData.pay_type == 2) {
                $rootScope.goods_cart.trade_type_code = '012';
            } else if (returnData.pay_type == 3) {
                $rootScope.goods_cart.trade_type_code = '016';
            }
            ngDialog.close(no_return_window);
            //根据购物车内容生成未结算的小票
            $rootScope.goods_cart.list.forEach(function (n) {
                if (n.daogou == '') {
                    n.daogou = $rootScope.user.UserCode;
                }
            });
            ReceiptRecord.add_no_ticket_return($rootScope.goods_cart).then(function (response) {
                if (response.data.status == 1 || response.data.status == '1') {
                    baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_REFUND_SUCCESS}); //'退款成功'
                    ReceiptRecord.update_skunum($rootScope.goods_cart.list, 1);
                    ReceiptRecord.update_record($rootScope.goods_cart.record_code);
                    GoodsCart.clear_cart();
                } else {
                    GoodsCart.clear_cart();
                    baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_REFUND_FAILS + $rootScope.language[response.data.code]}); //'退款失败：'
                }
            }).catch(function (err) {
                baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_REFUND_SUCCESS}); //'退款成功'
                ReceiptRecord.update_skunum($rootScope.goods_cart.list, 1);
                GoodsCart.clear_cart();
            });
            $scope.open_windows.pop();
        };
//         //PC版本快捷键部分 ======================================================
//         //f2库存查询 -----------------------------------------------------------/
//         shortCutAction.handler('/cashier/index', 'f2', function () {
//             $scope.$apply();
//             //只能打开一次
//             if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
//                 $scope.referInventory();
//             }
//         });
//         //f3定位到输入框 ---------------------------------------------------------/
//         shortCutAction.handler('/cashier/index', 'f3', function () {
//             $scope.$apply();
//             switch ($scope.open_windows[$scope.open_windows.length - 1]) {
//                 //打开库存查询窗口的回车：搜索商品
//                 case 'enquiry_selector':
//                     $scope.focus('enquiry_input');
//                     break;
//                 case 'main':
//                 default:
//                     $scope.focus();
//             }
//         });
//         //f4改数量 ------------------------------------------------------------/
//         shortCutAction.handler('/cashier/index', 'f4', function () {
//             $scope.$apply();
//             if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
//                 $scope.changeGoodsNum($scope.check_switch);
//                 $scope.focus();
//                 $scope.$apply();
//             }
//         });
//         //f5改折扣 ------------------------------------------------------------/
//         shortCutAction.handler('/cashier/index', 'f5', function () {
//             $scope.$apply();
//             if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
//                 $scope.changeGoodsRebate($scope.check_switch);
//                 $scope.focus();
//                 $scope.$apply();
//             }
//         });
//         //f6改单价 ------------------------------------------------------------/
//         shortCutAction.handler('/cashier/index', 'f6', function () {
//             $scope.$apply();
//             if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
//                 $scope.changeGoodsPrice($scope.check_switch);
//                 $scope.focus();
//                 $scope.$apply();
//             }



//         });
//         //f8收银按钮 -----------------------------------------------------------/
//         shortCutAction.handler('/cashier/index', 'f8', function () {
//             $scope.$apply();
//             $scope.go_settle();
//         });
//         //f9删行 --------------------------------------------------------------/
//         shortCutAction.handler('/cashier/index', 'f9', function () {
//             $scope.$apply();
//             if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
//                 $scope.goods_cart_remove($scope.check_switch);
//                 $scope.$apply();
//             }
//         });
//         //f10改金额 -----------------------------------------------------------/
//         shortCutAction.handler('/cashier/index', 'f10', function () {
//             $scope.$apply();
//             if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
//                 $scope.changeGoodsMoney($scope.check_switch);
//                 $scope.focus();
//                 $scope.$apply();
//             }
//         });
//         //f11促销 -----------------------------------------------------------/
//         shortCutAction.handler('/cashier/index', 'f11', function () {
//             $scope.$apply();
//             if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
//                 $scope.sales_prom();
//                 $scope.$apply();
//                 return;
//             }
//             if ($scope.open_windows[$scope.open_windows.length - 1] == 'sales_prom') {
//                 ngDialog.close(window_id);
//                 return;
//             }

//         });
//         //esc取消交易 ----------------------------------------------------------/
//         shortCutAction.handler('/cashier/index', 'esc', function () {
//             $scope.$apply();
//             switch ($scope.open_windows[$scope.open_windows.length - 1]) {
//                 //打开库存查询窗口的esc：关闭当前窗口
//                 case 'enquiry_selector':
//                     enquiry.close();
//                     $scope.clearInventory();
//                     break;
//                     //打开库存查询窗口的esc：关闭当前窗口
//                 case 'goods_select_stock':
//                     window_cur.close();
//                     break;
//                     //取单窗口关闭   
//                 case 'hold_receipt':
//                     window_id.close();
//                     break;
//                 case 'nothing':
//                     break;
//                 case 'main':
//                 default:
//                     $scope.goods_cart_clear();
//             }
//             $scope.$apply();
//         });
//         //回车键点击 -----------------------------------------------------------/
//         shortCutAction.handler('/cashier/index', 'enter', function () {
//             //从窗口栈中判断当前打开的窗口
//             switch ($scope.open_windows[$scope.open_windows.length - 1]) {
//                 //搜索框搜出多个商品时候的回车：确认商品
//                 case 'goods_selector':
//                     $scope.goods_select_click($scope.goods_select_data[$scope.goods_select_data_choose]);
//                     break;
//                     //打开库存查询窗口的回车：搜索商品
//                 case 'enquiry_selector':
//                     $scope.searchInventory($scope.input_keyword_inv, 0);
//                     break;
//                     //库存查询查出多个商品时候的回车：确认某商品的库存
//                 case 'goods_select_stock':
//                     $scope.goods_select_stock($scope.goods_select_data[$scope.goods_select_data_choose]);
//                     $scope.$apply();
//                     break;
//                     //取单窗口打开
//                 case 'hold_receipt':
//                     $scope.get_receipt_confirm($scope.get_receipt_index);
//                     break;
//                 case 'nothing':
//                     break;
//                 case 'main':
//                 default:
//                     $scope.btn_enter();
//                     $scope.$apply();
//             }
//         });
//         //上下键点击 ---------------------------------------------------------/
//         shortCutAction.handler('/cashier/index', 'down', function () {
//             $scope.$apply();
//             switch ($scope.open_windows[$scope.open_windows.length - 1]) {
//                 case 'goods_selector':
//                 case 'goods_select_stock':
//                     if ($scope.goods_select_data_choose < $scope.goods_select_data.length - 1) {
//                         $scope.goods_select_data_choose++;
//                         $scope.$apply();
//                     }
//                     break;
//                 case 'main':
//                 default:
//                     if ($scope.check_switch < $rootScope.goods_cart.list.length - 1) {
//                         $scope.check_switch++;
//                         $scope.$apply();
//                     }
//                     break;
//             }
//         });
//         shortCutAction.handler('/cashier/index', 'up', function () {
//             $scope.$apply();
//             switch ($scope.open_windows[$scope.open_windows.length - 1]) {
//                 case 'goods_selector':
//                 case 'goods_select_stock':
//                     if ($scope.goods_select_data_choose > 0) {
//                         $scope.goods_select_data_choose--;
//                         $scope.$apply();
//                     }
//                     break;
//                 case 'main':
//                 default:
//                     if ($scope.check_switch > 0) {
//                         $scope.check_switch--;
//                         $scope.$apply();
//                     }
//                     break;
//             }
//         });
//         //ctrl+f会员发卡----------------------------------------------------------------/
//         shortCutAction.handler('/cashier/index', 'ctrl+f', function () {
//             if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
//                 $scope.add_vip();
//                 $scope.$apply();
//             }
//         });
//         //ctrl+o打开钱箱----------------------------------------------------------------/
//         shortCutAction.handler('/cashier/index', 'ctrl+o', function () {
//             if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
//                 $scope.open_money_box();
//                 $scope.$apply();
//             }
//         });
//         //ctrl+q本店库存查询-----------------------------------------------------------/
//         shortCutAction.handler('/cashier/index', 'ctrl+q', function () {
//             //$scope.$apply();
//             if ($scope.open_windows[$scope.open_windows.length - 1] == 'enquiry_selector') {
//                 //设置为本店查询
//                 $scope.cur_shop();
//                 $scope.focus("enquiry_input");
//                 $scope.$apply();
//             }
//         });
//         //ctrl+w邻店库存查询-----------------------------------------------------------/
//         shortCutAction.handler('/cashier/index', 'ctrl+w', function () {
//             //$scope.$apply();
//             if ($scope.open_windows[$scope.open_windows.length - 1] == 'enquiry_selector') {
//                 $scope.nearly_shop()
//                 $scope.focus("enquiry_input");
//                 $scope.$apply();
//             }
//         });
// //        //ctrl+e总部库存查询-----------------------------------------------------------/
// //        shortCutAction.handler('/cashier/index', 'ctrl+e', function () {
// //            //$scope.$apply();
// //            if ($scope.open_windows[$scope.open_windows.length - 1] == 'enquiry_selector') {
// //                $scope.all_shop()
// //                $scope.focus("enquiry_input");
// ////                baison_app.api.alert({msg:3})
// //
// //                $scope.$apply();
// //            }
// //        });

//         //ctrl+t商品退换 -----------------------------------------------------------/
//         shortCutAction.handler('/cashier/index', 'ctrl+t', function () {
//             //$scope.$apply();
//             if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
//                 $scope.return_receipt();
//                 $scope.$apply();
//             }
//         });
//         //ctrl+h无票退货 -----------------------------------------------------------/
//         shortCutAction.handler('/cashier/index', 'ctrl+h', function () {
//             //$scope.$apply();
//             if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
//                 $scope.no_ticket_return();
//                 $scope.$apply();
//             }
//         });
//         //ctrl+s输入会员 -----------------------------------------------------------/
//         shortCutAction.handler('/cashier/index', 'ctrl+s', function () {
//             //$scope.$apply();
//             if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
//                 $scope.change_selector();
//                 $scope.focus();
//                 $scope.$apply();
//             }
//         });
//         //ctrl+m抹零 --------------------------------------------------------------/
//         shortCutAction.handler('/cashier/index', 'ctrl+m', function () {
//             //$scope.$apply();
//             if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
//                 $scope.cut_money();
//                 $scope.$apply();
//             }
//         });
//         //ctrl+g修改导购员 ---------------------------------------------------------/
//         shortCutAction.handler('/cashier/index', 'ctrl+g', function () {
//             //$scope.$apply();
//             if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
//                 baison_app.api.toast({msg: '批量修改导购员待开发'});
//             }
//         });
//         //ctrl+p挂单 ---------------------------------------------------------------/
//         shortCutAction.handler('/cashier/index', 'ctrl+p', function () {
//             //$scope.$apply();
//             if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
//                 $scope.hold_receipt();
//                 $scope.$apply();
//             }
//         });
//         //ctrl+1~8取单 -------------------------------------------------------------/
//         shortCutAction.handler('/cashier/index', 'ctrl+1', function () {
//             //$scope.$apply();
//             if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
//                 $scope.get_receipt(0);
//                 $scope.$apply();
//             }
//         });
//         shortCutAction.handler('/cashier/index', 'ctrl+2', function () {
//             //$scope.$apply();
//             if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
//                 $scope.get_receipt(1);
//                 $scope.$apply();
//             }
//         });
//         shortCutAction.handler('/cashier/index', 'ctrl+3', function () {
//             //$scope.$apply();
//             if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
//                 $scope.get_receipt(2);
//                 $scope.$apply();
//             }
//         });
//         shortCutAction.handler('/cashier/index', 'ctrl+4', function () {
//             //$scope.$apply();
//             if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
//                 $scope.get_receipt(3);
//                 $scope.$apply();
//             }
//         });
//         shortCutAction.handler('/cashier/index', 'ctrl+5', function () {
//             //$scope.$apply();
//             if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
//                 $scope.get_receipt(4);
//                 $scope.$apply();
//             }
//         });
//         shortCutAction.handler('/cashier/index', 'ctrl+6', function () {
//             //$scope.$apply();
//             if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
//                 $scope.get_receipt(5);
//                 $scope.$apply();
//             }
//         });
//         shortCutAction.handler('/cashier/index', 'ctrl+7', function () {
//             //$scope.$apply();
//             if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
//                 $scope.get_receipt(6);
//                 $scope.$apply();
//             }
//         });
//         shortCutAction.handler('/cashier/index', 'ctrl+8', function () {
//             //$scope.$apply();
//             if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
//                 $scope.get_receipt(7);
//                 $scope.$apply();
//             }
//         });
//         //ctrl+d删行 --------------------------------------------------------------/
//         shortCutAction.handler('/cashier/index', 'ctrl+d', function () {
//             $scope.$apply();
//             if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
//                 $scope.goods_cart_remove($scope.check_switch);
//                 $scope.$apply();
//             }
//         });
//         //ctrl+i礼券 --------------------------------------------------------------/
//         shortCutAction.handler('/cashier/index', 'ctrl+i', function () {
//             $scope.$apply();
//             if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
//                 $scope.search_coupon();
//                 $scope.focus();
//                 $scope.$apply();
//             }
//         });
        //PC版本快捷键结束 ======================================================//
        //监听扫描枪输入 ========================================================//
        $scope.saomiaoSwitch = false;
        $scope.saomiaoStart = 0;
        $scope.saomiaoEnd = 0;
        $scope.saomiaoInput = '';
        $scope.saomiaoTimer = null;
        $rootScope.saomiao = function (event) {
            $scope.btn_enter_switch = true;
            //console.log(event.keyCode);
            if ($scope.saomiaoTimer) {
                clearTimeout($scope.saomiaoTimer);
            }
            //开启扫描并记录扫描开始时间
            if (!$scope.saomiaoSwitch) {
                $scope.saomiaoStart = new Date().getTime();
                $scope.saomiaoInput = '';
            }
            $scope.saomiaoSwitch = true;
            $scope.saomiaoInput = $scope.saomiaoInput + String.fromCharCode(event.keyCode);

            $scope.saomiaoTimer = setTimeout(function () {
                $scope.saomiaoSwitch = false;
                $scope.saomiaoEnd = new Date().getTime();
                //3位以上且300毫秒以内认为是扫描枪录入
                if ($scope.saomiaoInput.length > 3 && ($scope.saomiaoEnd - $scope.saomiaoStart) < 800) {
                    $scope.btn_enter_switch = false;
                    $scope.saomiaoHandler($scope.saomiaoInput);
                    $scope.saomiaoInput = '';
                }
                $scope.btn_enter_switch = false;
            }, 500);
        };
        $scope.saomiaoHandler = function (input_saomiao) {
            //console.log(input_saomiao);
            //added by lqx maowei on 20170116 去除扫码器扫入商品码后面的空格和换行符
            $scope.input_keyword = $.trim(input_saomiao);
            $scope.btn_enter();
            $scope.$apply();
        };
        //============================================================================

//***********************************************************************************************************************
    }];
//结算界面控制器
var CashierSettleCtrl = ['$q','$scope', '$rootScope', '$location', 'GoodsCart', 'checkGetList', 'ReceiptRecord', 'ngDialog', 'WeiXin_ZF', 'ZhiFuBao_ZF', 'timeStamp2String', 'Print', 'SysConfig', 'tuiKu', 'Coupon', 'Cards', 'shortCutAction', 'commonInterface', 'ServiceOrder','dbGetOne', function ($q,$scope, $rootScope, $location, GoodsCart, checkGetList, ReceiptRecord, ngDialog, WeiXin_ZF, ZhiFuBao_ZF, timeStamp2String, Print, SysConfig, tuiKu, Coupon, Cards, shortCutAction, commonInterface, ServiceOrder,dbGetOne) {
        $scope.open_windows = ['main'];
        //获取的支付方式
        var check_list_result;
        //结算清单列表高度
        function Tbody_height() {
            var Settle_left_h = parseInt($("#Settle_left").css('height'));
            $("#Settle_left").find("#Tbody_box").css('height', Settle_left_h - 450 + 'px');
        }
        Tbody_height();

        GoodsCart.refresh_check();
        var type_num = '';
        //属性 ==================================================================//
        //支付列表的样式类
        $scope.checkclass = {
            '001': 'way_xj', '002': 'way_yhk', '003': 'way_lq', '004': 'way_vipjf',
            '005': 'way_vipczk', '006': '', '007': 'way_czk', '008': 'way_wxzf',
            '009': 'way_zfb', '010': 'way_wxzf', '011': 'way_zfb', '012': 'way_kdsc',
            '013': 'way_lhOK_card', '014': 'way_smt_card', '015': 'way_sd_card', '016': 'way_scVIP_card',
            '017': 'way_zft', '018': 'way_sccz_card', '019': 'way_scApp', '020': 'way_dzdp', '021': 'way_pf_card',
            '022': 'way_dgb', '023': 'way_ds_card', '024': 'way_kb_card','025': 'way_bq_card',
			'103': 'way_feifan_pay', 'more': 'way_more', 'back': 'way_return'
        };
        //默认空为默认样式  已经使用为active  不可用为disable
        $scope.activecheckclass = {//101   米雅支付
            '001': '', '002': '', '003': '', '004': '',
            '005': '', '006': '', '007': '', '008': '',
            '009': '', '010': '', '011': '', '012': '',
            '013': '', '014': '', '015': '', '016': '',
            '017': '', '018': '', '019': '', '020': '', 
			'021': '', '022': '', '023': '', '024': '',
			'025': '', '103': '', 'more': '', 'back': ''
        };
        $scope.configData = $api.getStorage('configData');
        //当前系统启用的支付方式列表
        $scope.checklistData = {};
        //当前系统启用的常用支付列表
        $scope.common_checklistData = {};
        //当前系统启用的不常用的支付列表
        $scope.uncommon_checklistData = {};
        //确认按钮disable状态
        $scope.submitDisable = true;
        //显示更多按钮
        var show_more_btn = function () {
            $scope.checklistData['more'] = {'CheckName': $rootScope.language.TIPS_CASHIER_MORE, 'CheckCode': 'more'};
        };

        //显示返回按钮
        var show_back_btn = function () {
            $scope.checklistData['back'] = {'CheckName': $rootScope.language.ACT_BACK, 'CheckCode': 'back'};
        };
        //获取收银方式列表
        checkGetList.get_list().then(function (response) {
            $scope.check_foreign = response.currencyType;
            check_list_result = response.checkType;
            var len = 0;
            var pay_num = $scope.configData.commonpay_num;
            var configData = $api.getStorage('configData');
            check_list_result.forEach(function (n) {
                var CheckOrder = configData.old_order[n.CheckCode] * 1;
                if (CheckOrder < 10) {
                    CheckOrder = '00' + CheckOrder;
                } else if (CheckOrder < 100) {
                    CheckOrder = '0' + CheckOrder;
                }
                if (-1 != $scope.configData.checklist.indexOf(n.CheckCode)) {
                    len++;
                    if (len <= pay_num) {
                        $scope.checklistData[CheckOrder] = n;
                        $scope.common_checklistData[n.CheckCode] = n;
                    } else {
                        show_more_btn(len);
                        $scope.uncommon_checklistData[n.CheckCode] = n;
                        $scope.uncommon_checklistData[n.CheckCode].type = 'more';
                    }
                }
            });
        });
        //获取小票商品明细信息
        var get_goods_detail_infos = function(){
            var deferred = $q.defer();
            var promise = deferred.promise;
            $rootScope.goods_cart.list.forEach(function(n,i){
                deferred[i] = $q.defer();
                promise[i] = deferred[i].promise;
                dbGetOne('select weight,unit_name from PosGoods where GoodsCode="' + n.GoodsCode + '"').then(function(ret){
                    n.weight = ret.weight;
                    n.unit_name = ret.unit_name;
                    deferred[i].resolve('success');
                });
               
            });
            return $q.all(promise);
        };
        //获取小票信息
        var xp_getinfo = function () {
            var record = {};
            var configData = $api.getStorage('configData');
            var printData = configData.printData;
            var shop_addr = '';
            var shop_tel = '';
            var web_site = '';
            if (printData != undefined) {
                shop_addr = printData['addr'];
                shop_tel = printData['tel'];
                web_site = printData['web_site'];
            }
            var arr_guides = [];
            $rootScope.goods_cart.list.forEach(function (n) {
                var user_name = '';
                if (typeof n.daogou != 'object') {
                    $rootScope.goods_cart.guidelist.filter(function (guide) {
                        if (guide.UserCode == n.daogou) {
                            user_name = guide.UserName;
                        }
                    });
                } else {
                    user_name = n.daogou.UserName;
                }
                arr_guides.push({
                    'guide_user_name': user_name,
                });
            });

            record.record_code = $rootScope.goods_cart.record_code;
            record.record_time = timeStamp2String(0, 'datetime');
            record.vip_code = $rootScope.goods_cart.vip.vip_code;
            record.pay_money = $rootScope.goods_cart.info.final_money;
            record.total_num = $rootScope.goods_cart.info.total_num;
            record.total_money = $rootScope.goods_cart.info.total_money;
            record.record_detail = $rootScope.goods_cart.list;
            record.payment = $rootScope.goods_cart.checklist;
            record.shop_name = $rootScope.current_shop.ShopName;
            record.user_code = $rootScope.user.UserCode;
            record.guide_user_name = commonInterface.get_guides_user_name(arr_guides);
            record.user_name = $rootScope.user.UserName;
            record.brand_name = $rootScope.company_info.brand_name;
            record.shop_addr = shop_addr;
            record.shop_tel = shop_tel;
            record.web_site = $rootScope.company_info.website;
            if (record.payment.length == 0) {
                record.payment = [{'code': '', 'pay_money': ''}];
            }
            
            var deferred = $q.defer();
            var promise = deferred.promise;
            get_goods_detail_infos().then(function(){
                record.record_detail = $rootScope.goods_cart.list;
                deferred.resolve(record);
            });
            return promise;
        };
        //打印小票预览内容信息
        var xp_preview = function () {
            $scope.printData = {};
            //获取小票模版的名称
            var tpl_name = '';
            $scope.printData.info = '';
            var configData = $api.getStorage('configData');
            if (configData.printData != null && configData.printData != undefined) {
                tpl_name = configData.printData['selectvalue'].name;
            }

            Print.xp_select_tplcontent(tpl_name).then(function (ret) {
                var tpl_str = '';
                if (ret[0] != undefined && ret[0].content != undefined && ret[0].content != null) {
                    tpl_str = ret[0].content;
                }
                //var record = xp_getinfo();
                xp_getinfo().then(function(record){
                    Print.xp_print_tpl_to_string('', tpl_str, record, function (data) {
                        $scope.printData.info = data;
                    });
                });
                
            });
        };
        //方法================================================================
        /**
         * 根据当前支付状况 设置收银列表样式开关 以及不同收银方式的冲突状态
         * @author jhua.zuo <jhua.zuo@baisonmail.com>
         * @date 2015-11-09
         */
        //获取支付方式名字
        var getCheckName = function (ret) {
            var CheckName = '';
            for (var i in check_list_result) {
                if (check_list_result[i].CheckCode == ret) {
                    return CheckName = check_list_result[i].CheckName;
                }
            }

        };
        var set_checkclass = function () {
            $scope.activecheckclass = {
                '001': '', '002': '', '003': '', '004': '',
                '005': '', '006': '', '007': '', '008': '',
                '009': '', '010': '', '011': '', '012': '',
                '013': '', '014': '', '015': '', '016': '',
                '017': '', '018': '', '019': '', '020': '',
                '021': '', '022': '', '023': '', '024': '',
				'025': '','103': '','more': '',
                'back': ''
            };
            if ($rootScope.goods_cart.vip.vip_code == '') {
                //未选择VIP则不可以使用VIP储值卡和VIP积分
                $scope.activecheckclass['004'] = 'disable';
//              $scope.activecheckclass['005'] = 'disable';
            }

            $rootScope.goods_cart.checklist.forEach(function (e, index) {
                //现金、银行卡、VIP储值卡不可与 微信、支付宝同时使用
                //微信、支付宝不能互相同时使用
                //积分、优惠券不受影响，退单时不退
                switch (e.code) {
//                  case '001':
//                  case '002':
                    case '005':
                        $scope.activecheckclass['008'] = 'disable';
                        $scope.activecheckclass['009'] = 'disable';
                        $scope.activecheckclass['010'] = 'disable';
                        $scope.activecheckclass['011'] = 'disable';
                        break;
                    case '008':
//                      $scope.activecheckclass['001'] = 'disable';
//                      $scope.activecheckclass['002'] = 'disable';
//                      $scope.activecheckclass['005'] = 'disable';
                        $scope.activecheckclass['009'] = 'disable';
                        $scope.activecheckclass['010'] = 'disable';
                        $scope.activecheckclass['011'] = 'disable';
                        break;
                    case '009':
//                      $scope.activecheckclass['001'] = 'disable';
//                      $scope.activecheckclass['002'] = 'disable';
//                      $scope.activecheckclass['005'] = 'disable';
                        $scope.activecheckclass['008'] = 'disable';
                        $scope.activecheckclass['010'] = 'disable';
                        $scope.activecheckclass['011'] = 'disable';
                        break;
                    case '010':
//                      $scope.activecheckclass['001'] = 'disable';
//                      $scope.activecheckclass['002'] = 'disable';
//                      $scope.activecheckclass['005'] = 'disable';
                        $scope.activecheckclass['008'] = 'disable';
                        $scope.activecheckclass['009'] = 'disable';
                        $scope.activecheckclass['011'] = 'disable';
                        break;
                    case '011':
//                      $scope.activecheckclass['001'] = 'disable';
//                      $scope.activecheckclass['002'] = 'disable';
//                      $scope.activecheckclass['005'] = 'disable';
                        $scope.activecheckclass['008'] = 'disable';
                        $scope.activecheckclass['009'] = 'disable';
                        $scope.activecheckclass['010'] = 'disable';
                        break;
                }
                $scope.activecheckclass[e.code] = 'active';
            });
            //小票预览
            xp_preview();
        };
        set_checkclass();
        //现金收银 ------------------------------------------------
        $scope.check_window_close = function () {
            ngDialog.close(check_window);
        };
        var check_window = 0; //弹出窗口ID
        //打开钱箱
        var open_money_box = function () {
            var systype = baison_app.api.systemType;
            if (systype == 'ios') {
                var configData = $api.getStorage('configData');
                var pay_type = configData.zftd;
                if (pay_type == 1) { //是盒子支付
                    baison_app.boxPay.openMoneyBox(function (ret, err) {
                        baison_app.api.toast({msg: ret.message});
                    });
                } else {
                }
            }else if (systype == 'android') {
                //飞凡设备
				var configData = $api.getStorage('configData');
                if (configData.feifan.switch == 1) {
                    baison_app.feifanPrint.selectDevice(function () {//开启打印机
                        baison_app.feifanPrint.openBox(function (ret, err) {
                            baison_app.feifanPrint.closeDevice(function (ret, err) {//关闭打印机
                            });
                        });
                    });
                }
            }

        };
        var check_001_xianjin = function () {
            //冲突检测
            if (GoodsCart.has_check(['001'])) {
                baison_app.api.toast({msg: $rootScope.language.MSG_YOU_HAVE_USE_CASHIER}); //'您已经使用过现金收银了!'
                return;
            }

            if ($scope.activecheckclass['001'] == 'disable') {
                return;
            }
            //打开钱箱
            open_money_box();
            $scope.xianjinData = {};
            var selected_check_foreign = '';
            check_window = ngDialog.open({closeByDocument: false,
                template: './html/cashier/dialog/check_001_xianjin.html',
                disableAnimation: true,
                trapFocus: false,
                scope: $scope,
                preCloseCallback: function () {
                    $scope.open_windows.pop();
                },
                controller: ['$scope', '$rootScope', function ($scope, $rootScope) {
                        var configData = $api.getStorage('configData');
                        $scope.checked_foreign_coin = []
                        $scope.currency_foreign = configData.currency_foreign;
                        if ($scope.configData.currency_foreign == 1) {
                            $scope.check_foreign.forEach(function (n) {
                                if (-1 != $scope.configData.currencylist.indexOf(n.cur_code)) {
                                    $scope.checked_foreign_coin.push(n);
                                    n.checked = 0;
                                    if (n.cur_code == configData.standard_coin) {
                                        n.checked = 1;
                                        $scope.standard_setting = n;
                                        $scope.standard_setting_code = n.cur_code;
                                        $scope.standard_selected = n;
                                        $scope.standard_selected_code = n.cur_code;
                                    }
                                }

                            });
                        } else {
                            $scope.standard_setting = {};
                            $scope.standard_selected = {};
                            $scope.standard_setting.rate = 1;
                            $scope.standard_selected.rate = 1;
                        }
                        $scope.input_radio = $scope.configData.standard_coin;
                        $scope.get_rate = function (rate) {
                            $scope.standard_selected = rate;
                            $scope.input_radio = rate.cur_code;
                            $scope.standard_selected_code = rate.cur_code;
                        };
                        $scope.xianjinData.money = '';
                        $scope.change_001_xianjin_input = function () {
                            var integral = $scope.xianjinData.money;
                            var re = /^([0-9]\d*.\d*|[0-9]\d*)$/;
                            if (integral != undefined && integral != null && integral != '') {
                                if (!re.test(integral)) {
                                    baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_INPUT_VALID_AMOUNT}); //'请输入一个有效的金额'
                                    $scope.xianjinData.money = '';
                                    $scope.xianjinData.charge_money = 0.00;
                                    return;
                                }
                            } else {
                                baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_INPUT_VALID_AMOUNT}); //'请输入一个有效的金额'
                                return;
                            }

                            var charge_money = $scope.xianjinData.money * $scope.standard_selected.rate / $rootScope.StandardRate - $rootScope.goods_cart.info.daifu_money;
                            $scope.xianjinData.charge_money = (charge_money > 0) ? charge_money : 0.00;
                        };
                    }]
            });
        };
        $scope.check_001_xianjin_submit = function (payData, rate) {
            //数据整理
            var pay_money, final_money, charge_money, remark;
            if (payData.money == undefined || payData.money == null || payData.money == '' || payData.money == 0) {
                baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_INPUT_AMOUNT}); //'请输入付款金额'
                return;
            }
            pay_money = parseFloat(payData.money * rate / $rootScope.StandardRate);
            charge_money = parseFloat(payData.charge_money * rate / $rootScope.StandardRate);
            $rootScope.goods_cart.info.charge_money = charge_money;
            final_money = parseFloat(pay_money - charge_money);
            remark = $rootScope.language.MSG_CASH_TO_RECEIVE + pay_money.toFixed(2) + $rootScope.language.MSG_CASH_TO_CHANGE + charge_money.toFixed(2); //'现金收：''；找零：'
            //添加数据
            GoodsCart.add_check('001', getCheckName('001'), pay_money, final_money, '', remark);
            //支付完毕状态检测
            $scope.submitDisable = !GoodsCart.is_pay_over();
            set_checkclass();
            ngDialog.close(check_window);
//            $scope.open_windows.pop();
        };
        //获取支付卡名称 根据 支付卡类型
        var get_pay_card_type = function (num) {
            return $scope.checklistData[num].CheckName;
        };
        //其他卡形式
        var check_012_card = function () {
            //冲突检测
            var num = type_num;
            $scope.card_name = get_pay_card_type(num);
            if (GoodsCart.has_check([num])) {
                baison_app.api.toast({msg: $scope.card_name + $rootScope.language.TIP_RECEIPR}); //'您已经使用过现金收银了!'
                return;
            }

            if ($scope.activecheckclass[num] == 'disable') {
                return;
            }
            $scope.cardData = {};
            //$scope.cardData.num = num;
            check_window = ngDialog.open({closeByDocument: false,
                template: './html/cashier/dialog/check_012_card.html',
                disableAnimation: true,
                trapFocus: false,
                scope: $scope,
                controller: ['$scope', '$rootScope', function ($scope, $rootScope) {
                        $scope.cardData.money = '';
                        $scope.change_012_card_input = function () {
                            var integral = $scope.cardData.money;
                            var re = /^([0-9]\d*.\d*|[0-9]\d*)$/;
                            if (integral != undefined && integral != null && integral != '') {
                                if (!re.test(integral)) {
                                    baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_INPUT_VALID_AMOUNT}); //'请输入一个有效的金额'
                                    $scope.cardData.money = '';
                                    $scope.cardData.charge_money = 0.00;
                                    return;
                                }
                            } else {
                                baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_INPUT_VALID_AMOUNT}); //'请输入一个有效的金额'
                                return;
                            }

                            var charge_money = $scope.cardData.money - $rootScope.goods_cart.info.daifu_money;
                            $scope.cardData.charge_money = (charge_money > 0) ? charge_money : 0.00;
                        };
                    }]
            });
        };
        $scope.check_012_card_submit = function (payData) {
            //数据整理
            var num = type_num;
            var pay_name = get_pay_card_type(num);
            var pay_money, final_money, charge_money, remark;
            if (payData.money == undefined || payData.money == null || payData.money == '' || payData.money == 0) {
                baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_INPUT_AMOUNT}); //'请输入付款金额'
                return;
            }
            pay_money = parseFloat(payData.money);
            charge_money = parseFloat(payData.charge_money);
            $rootScope.goods_cart.info.charge_money = charge_money;
            final_money = parseFloat(pay_money - charge_money);
            remark = pay_name + $rootScope.language.TIP_GET + pay_money.toFixed(2) + $rootScope.language.MSG_CASH_TO_CHANGE + charge_money.toFixed(2); //'现金收：''；找零：'
            //添加数据
            GoodsCart.add_check(num, getCheckName(num), pay_money, final_money, '', remark);
            //支付完毕状态检测
            $scope.submitDisable = !GoodsCart.is_pay_over();
            set_checkclass();
            ngDialog.close(check_window);
//            $scope.open_windows.pop();
        };
        $scope.check_012_card_window_close = function () {
            ngDialog.close(check_window);
        };
        //更多按钮功能
        var check_more_pay = function () {
            $scope.checklistData = {};
            $scope.checklistData = $scope.uncommon_checklistData;
            show_back_btn();
        };
        //返回按钮功能
        var check_back_pay = function () {
            $scope.checklistData = {};
            $scope.checklistData = $scope.common_checklistData;
            show_more_btn();
        };
        //是否回到常用支付列表

        //银行卡 -------------------------------------------------
        var yinhangka_pay_over = function (payData) {
            //数据整理
            var pay_money, final_money, remark, coupon_code;
            final_money = pay_money = parseFloat(payData.money);
            remark = $rootScope.language.MSG_BOX_SERIAL_NUM + payData.hezi_code; //'盒子流水号'
            coupon_code = payData.coupon_code; //TODO 此处应该存银行卡的交易流水号
            //添加数据
            GoodsCart.add_check('002', getCheckName('002'), pay_money, final_money, coupon_code, remark);
            //支付完毕状态检测
            GoodsCart.is_pay_over();
            set_checkclass();
            //直接结算收银
            //$scope.submit_click();
        };
        //盒子支付完成
        var yinhangka_hezi_pay_over = function (payData) {
            //数据整理
            var pay_money, final_money, remark, coupon_code;
            final_money = pay_money = parseFloat(payData.money);
            remark = $rootScope.language.MSG_BOX_SERIAL_NUM + payData.hezi_code; //'盒子流水号'
            coupon_code = payData.coupon_code; //TODO 此处应该存银行卡的交易流水号
            //添加数据
            GoodsCart.add_check('002', getCheckName('002'), pay_money, final_money, coupon_code, remark);
            //支付完毕状态检测
            GoodsCart.is_pay_over();
            set_checkclass();
            //直接结算收银
            $scope.submit_click();
        };
        var check_002_yinhangka_local = function () {
            $scope.yinhangkaData = {};
            check_window = ngDialog.open({closeByDocument: false,
                trapFocus: false,
                template: './html/cashier/dialog/check_002_yinhangka.html',
                disableAnimation: true,
                scope: $scope,
                preCloseCallback: function () {
                    $scope.open_windows.pop();
                },
                controller: ['$scope', '$rootScope', function ($scope, $rootScope) {
                        $scope.change_002_yinghangka_input = function () {
                            var integral = $scope.yinhangkaData.money;
                            //baison_app.api.alert({msg:integral,title:'yinhangka'});
                            var re = /^([0-9]\d*.\d*|[0-9]\d*)$/;
                            if (integral != undefined && integral != null && integral != '') {
                                if (!re.test(integral)) {
                                    baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_INPUT_VALID_AMOUNT}); //'请输入一个有效的金额'
                                    $scope.yinhangkaData.money = '';
                                    return;
                                }
                            } else {
                                baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_INPUT_VALID_AMOUNT}); //'请输入一个有效的金额'
                                return;
                            }
                            if ($scope.yinhangkaData.money > $rootScope.goods_cart.info.daifu_money) {
                                $scope.yinhangkaData.money = parseFloat($rootScope.goods_cart.info.daifu_money).toFixed(2);
                            }

                        };
                    }]
            });
        };
        //验签盒子支付
        var check_baison_sign = function (box_info) {
            var sign = 'BAISON' + box_info.pay_key + '###' + box_info.app_code + '***' + '8888';

            var baison_sign = $.md5(sign);// MD5(BAISON+APIKEY+###+APPCODE+***+8888)
            if (baison_sign != box_info.baison_key) {
                return 0;
            }
            return 1;
        };
        //盒子支付方式
        var check_002_yinhangka_hezi = function (box_info) {
            if (!check_baison_sign(box_info)) {
                baison_app.api.alert({msg: $rootScope.language.TIP_USER_SIGN_WRONG});
                return;
            }
            var money = Number($rootScope.goods_cart.info.daifu_money * 100);
            var record_code = $rootScope.goods_cart.record_code;
            if (box_info == '') { //测试接口
                baison_app.boxPay.cardPay({orderAmount: money, orderNo: record_code}, function (ret, err) {
                    if (ret.status == '1') {
                        var payData = {};
                        payData.money = $rootScope.goods_cart.info.daifu_money;
                        payData.coupon_code = ret.data.outTradeNo; //自身流水号
                        payData.hezi_code = ret.data.tradeNo; //盒子流水号
                        yinhangka_hezi_pay_over(payData);
                    }
                    if (err) {
                        baison_app.api.toast({msg: err.message.errorCode});
                    } else {
                        baison_app.api.toast({msg: ret.message});
                    }
                });
            } else {//正式接口
                baison_app.boxPay.cardPay({orderAmount: money, orderNo: record_code, API_KEY: box_info.pay_key, TPF_URL: box_info.pay_url, APP_CODE: box_info.app_code, MD5_KEY: box_info.md5_key}, function (ret, err) {
                    if (ret.status == '1') {
                        var payData = {};
                        payData.money = $rootScope.goods_cart.info.daifu_money;
                        payData.coupon_code = ret.data.outTradeNo; //自身流水号
                        payData.hezi_code = ret.data.tradeNo; //盒子流水号
                        yinhangka_hezi_pay_over(payData);
                    }

                    if (err) {
                        baison_app.api.toast({msg: err.message.errorCode});
                    } else {
                        baison_app.api.toast({msg: ret.message});
                    }

                });
            }


        };
        //现金收银 兼容盒子支付方式
        var check_002_yinhangka = function () {

            if (GoodsCart.has_check(['002'])) {
                baison_app.api.toast({msg: $rootScope.language.MSG_YOU_HAVE_USE_BANK_CASHIER}); //'您已经使用过银行卡收银了!'
                return;
            }

            if ($scope.activecheckclass['002'] == 'disable') {

                return;
            }
            //判断是否是盒子支付方式
            var systype = baison_app.api.systemType;
            if (systype == 'ios') { //盒子支付 暂时支持ios
                var configData = $api.getStorage('configData');
                var pay_type = configData.zftd;
                if (pay_type == 1) { //是盒子支付
                    if (!window.navigator.onLine) {
                        baison_app.api.toast({msg: $rootScope.language.TIPS_NO_NET_NO_BOX_PAY});
                        return;
                    }
                    SysConfig.get_box_config().then(function (ret) {
                        //baison_app.api.alert({msg: ret.data, title: 'boxinfo'});
                        if (ret.data.status == 1) {
                            var box_info = {};
                            box_info.pay_key = ret.data.data.box_port_key;
                            box_info.pay_url = ret.data.data.box_port_url.replace(/\\/g, "");
                            box_info.app_code = ret.data.data.box_app_code;
                            box_info.md5_key = ret.data.data.box_md5_key;
                            box_info.baison_key = ret.data.data.box_baison_key;
                            check_002_yinhangka_hezi(box_info);
                        }


                    }).catch(function (err) {
                        baison_app.api.toast({msg: $rootScope.language.MSG_NETWORK_ABNORMAL});
                        var box_info = '';
                        check_002_yinhangka_hezi(box_info);
                    });
                    return;
                }
            }
            //本土支付方式
            check_002_yinhangka_local();
        };
        $scope.check_002_yinhangka_submit = function (payData) {
            //数据整理
            if (payData.money == undefined || payData.money == null || payData.money == '' || payData.money == 0) {
                baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_INPUT_AMOUNT}); //'请输入付款金额'
                return;
            }
            var pay_money, final_money, remark, coupon_code;
            final_money = pay_money = parseFloat(payData.money);
            remark = '';
            coupon_code = ''; //TODO 此处应该存银行卡的交易流水号
            //添加数据
            GoodsCart.add_check('002', getCheckName('002'), pay_money, final_money, coupon_code, remark);
            //支付完毕状态检测
            $scope.submitDisable = !GoodsCart.is_pay_over();
            set_checkclass();
            ngDialog.close(check_window);
//            $scope.open_windows.pop();
        };
        //优惠券 -------------------------------------------------
        var check_003_youhuiquan = function () {
            if ($scope.activecheckclass['003'] == 'disable') {
                return;
            }
            var isbut = false; //是否点击使用按钮
            $scope.youhuiquanData = {};
            var oldcode = $scope.youhuiquanData.coupon;
            check_window = ngDialog.open({closeByDocument: false,
                trapFocus: false,
                template: './html/cashier/dialog/check_003_youhuiquan.html',
                disableAnimation: true,
                scope: $scope,
                preCloseCallback: function () {
                    $scope.open_windows.pop();
                },
                controller: ['$scope', '$rootScope', function ($scope, $rootScope) {
                        //输入优惠券代码，查询抵扣金额
                        //TODO 需要从api接口获取
                        $scope.check_youhuiquan_input = function (code) {
                            if (code == undefined || code == null || code == '') {
                                baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_ENTER_COUPON}); //'请输入优惠券'
                                return;
                            }
                            if (oldcode != code) {
                                isbut = true;
                                oldcode = code;
                            }

                            var param = {};
                            param.coupon = $scope.youhuiquanData.coupon;
                            param.vip_code = $rootScope.goods_cart.vip.vip_code;
                            //根据api获取优惠券信息ret
                            if (isbut) {
                                ReceiptRecord.youhuiquan_add(param).then(function (ret) {
                                    var coupon_money = 0;
                                    if (ret.data.status === 1) {
                                        if (ret.data.data.detail.end_time < timeStamp2String(new Date(), 'datetime')) {
                                            baison_app.api.toast({msg: $rootScope.language.MSG_COUPON_OVER_TIME}); //'该优惠券已过期'
                                            return;
                                        }
                                        //判断优惠券是否已使用过
                                        if (ret.data.data.detail.is_use == 1) {
                                            baison_app.api.toast({msg: $rootScope.language.MSG_COUPON_IS_USE}); //'该优惠券已被使用过'
                                            return;
                                        }
                                        //判断优惠券是否被作废
                                        if (ret.data.data.detail.is_cancel == 1) {
                                            baison_app.api.toast({msg: $rootScope.language.MSG_COUPON_IS_INVALID}); //'优惠券已被作废'
                                            return;
                                        }

                                        if (ret.data.data.detail.vip_code != $rootScope.goods_cart.vip.vip_code && ret.data.data.detail.is_accept == 1) {
                                            baison_app.api.toast({msg: $rootScope.language.MSG_COUPON_IS_USE_HAVENT_ROOT}); //'优惠券已被领用，你没有权限使用'
                                            return;
                                        }
                                        //判断是否在优惠券的使用时间内
                                        if (typeof ret.data.data.detail.start_time !== 'string' || typeof ret.data.data.detail.end_time !== 'string') {
                                            var day = timeStamp2String(new Date(), 'datetime');
                                            var start_time = timeStamp2String(ret.data.data.detail.start_time, 'datetime');
                                            var end_time = timeStamp2String(ret.data.data.detail.end_time, 'datetime');
                                            if (!(day >= start_time && day <= end_time)) {
                                                baison_app.api.toast({msg: $rootScope.language.MSG_COUPON_IS_OVER_TIME}); //'该优惠券不在使用日期内'
                                                return;
                                            }
                                        }
                                        //判断券的类型是不是抵扣券和随机金额券
                                        if (ret.data.data.coupon.type != '0' && ret.data.data.coupon.type != '3') {
                                            baison_app.api.toast({msg: $rootScope.language.MSG_SORRY_COUPON_IS_NOT_RULE}); //'对不起，优惠券不符合规则'
                                            ngDialog.close(check_window);
                                            return;
                                        }
                                        //判断优惠券是否关联促销
                                        if (ret.data.data.coupon.promo_id != "") {
                                            baison_app.api.toast({msg: $rootScope.language.MSG_SORRY_COUPON_IS_NOT_RULE}); //'对不起，优惠券不符合规则'
                                            ngDialog.close(check_window);
                                            return;
                                        }

                                        isbut = false;
                                        if (ret.data.data.balance_money == undefined) {
                                            coupon_money = parseFloat(ret.data.data.detail.money).toFixed(2);
                                        } else {
                                            coupon_money = parseFloat(ret.data.data.balance_money).toFixed(2);
                                        }

                                    } else {
                                        baison_app.api.toast({msg: $rootScope.language[ret.data.code]});
                                        $scope.youhuiquanData.coupon = '';
                                        isbut = true;
                                    }
                                    $scope.youhuiquanData.money = coupon_money;
                                });
                            }
                        };
                    }]
            });
        };
        var is_use_youhuiquan = function (coupon) {
            for (var i = 0; i < $rootScope.goods_cart.checklist.length; i++) {
                if ($rootScope.goods_cart.checklist[i].coupon_code == coupon) {
                    return 1;
                }
            }
            return 0;
        };
        $scope.check_003_youhuiquan_submit = function (payData) {
            //是否可以使用
            if (is_use_youhuiquan(payData.coupon) == 1) {
                baison_app.api.toast({msg: $rootScope.language.MSG_COUPON_IS_USE}); //'该优惠券已使用'
                return;
            }
            //数据整理
            var pay_money, final_money, remark, coupon_code;
            if (payData.money == undefined || payData.money == null || payData.money == '' || payData.money == 0) {
                baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_ENTER_COUPON}); //'请输入优惠券'
                return;
            }

            pay_money = parseFloat(payData.money);
            if (pay_money == 0 || pay_money == null) {
                baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_ENTER_COUPON}); //'请输入优惠券'
                return;
            }
            final_money = (payData.money > $rootScope.goods_cart.info.daifu_money) ? $rootScope.goods_cart.info.daifu_money : payData.money;
            final_money = parseFloat(final_money);
            pay_money = final_money;
            remark = $rootScope.language.MSG_COUPON + payData.coupon + $rootScope.language.MSG_DENOMINATION + payData.money; //'优惠券：''；面额：'
            coupon_code = payData.coupon;
            //添加数据
            GoodsCart.add_check('003', getCheckName('003'), pay_money, final_money, coupon_code, remark);
            //支付完毕状态检测
            $scope.submitDisable = !GoodsCart.is_pay_over();
            set_checkclass([]);
            ngDialog.close(check_window);
//            $scope.open_windows.pop();
        };
        //VIP积分 ------------------------------------------------

        var check_004_jifen = function () {
            //冲突检测
            if (GoodsCart.has_check(['004'])) {
                baison_app.api.toast({msg: $rootScope.language.MSG_YOU_HAVE_USE_POINTS_DEDUCTION}); //'您已经使用过积分抵扣了!'
                $scope.open_windows.pop();
                return;
            }

            if ($rootScope.goods_cart.vip.vip_code == '') {
                baison_app.api.toast({msg: $rootScope.language.MSG_NOT_CHOOSE_MEMBER_CANT_USE_INTE}); //'您尚未选择会员，不能使用积分!'
                $scope.open_windows.pop();
                return;
            }

            if ($scope.activecheckclass['004'] == 'disable') {
                $scope.open_windows.pop();
                return;
            }


            $scope.jifenData = {};
            check_window = ngDialog.open({closeByDocument: false,
                trapFocus: false,
                template: './html/cashier/dialog/check_004_jifen.html',
                disableAnimation: true,
                scope: $scope,
                preCloseCallback: function () {
                    $scope.open_windows.pop();
                },
                controller: ['$scope', '$rootScope', function ($scope, $rootScope) {
                        //输入积分，查询抵扣金额
                        $scope.check_jifen_input = function (code) {
                            /*var integral = new Number(code);
                             if(isNaN(integral)||integral<=0){
                             baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON],msg:'请输入一个有效的积分'});
                             return;
                             }*/
                            var integral = code;
                            var re = /^[1-9]+[0-9]*$/;
                            if (!re.test(integral)) {
                                baison_app.api.toast({msg: $rootScope.language.MSG_ENTER_VALID_POINTS}); //'请输入一个有效的积分'
                                $scope.jifenData.integral = '';
                                return;
                            }

                            var current_vip = $rootScope.goods_cart.vip;
                            if ((integral - current_vip.vip_integral) > 0) {
                                baison_app.api.toast({msg: $rootScope.language.MSG_HAVINT_ENOUGH_USE_POINT}); //'您没有足够的可用积分'
                                $scope.jifenData.integral = '';
                                return;
                            }
                            /*if (parseInt(integral) < parseInt(current_vip.to_money_unit)) {
                             baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON],msg:'输入积分不能小于最小单位'});
                             return;
                             }
                             
                             var money = Math.floor(integral / current_vip.to_money_unit) * current_vip.to_money_value;*/


                            var param = {};
                            param.vip_code = current_vip.vip_code;
                            param.source = 6;
                            param.integral = integral;
                            param.record_detail = 1;
                            param.shop_code = $rootScope.current_shop.ShopCode;
                            param.je = $rootScope.goods_cart.info.daifu_money;
                            var record_code = $rootScope.goods_cart.record_code;
                            ReceiptRecord.get_one_local(record_code).then(function (record_data) {
                                param.record_data = record_data.record_detail;
                                ReceiptRecord.vipjifen_add(param).then(function (ret) {
                                    if (ret.data.status == 1) {
                                        money = ret.data.data.money;
                                    } else {
                                        baison_app.api.toast({msg: $rootScope.language[ret.data.code]});
                                        return;
                                    }
                                    //剩余待支付金额
                                    var daifu = $rootScope.goods_cart.info.daifu_money;
                                    //多余积分不找零
                                    if (money > daifu) {
                                        money = daifu;
                                    }
                                    $scope.jifenData.money = money;
                                });
                            });

                            
                        };
                    }]
            });
        };
        $scope.check_004_jifen_submit = function (payData) {
            //数据整理
            var pay_money, final_money, remark, coupon_code;
            pay_money = parseFloat(payData.money);
            if (pay_money == 0 || payData.money == null || payData.integral == undefined) {
                baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_INPUT_USE_POINTS}); //'请输入使用积分'
                return;
            }
            final_money = (payData.money > $rootScope.goods_cart.info.daifu_money) ? $rootScope.goods_cart.info.daifu_money : payData.money;
            final_money = parseFloat(final_money);
            remark = $rootScope.language.MSG_POINTS_USE + payData.integral + $rootScope.language.MSG_INTEGRAL_TO_NOW + parseFloat(payData.money).toFixed(2); //'使用' '积分抵现' 
            coupon_code = payData.integral;
            //添加数据
            GoodsCart.add_check('004', getCheckName('004'), pay_money, final_money, coupon_code, remark);
            $scope.submitDisable = !GoodsCart.is_pay_over();
            set_checkclass();
            ngDialog.close(check_window);
//            $scope.open_windows.pop();
        };
        //VIP储值卡

        var check_005_vipczk = function () {
            //冲突检测
            if (GoodsCart.has_check(['005'])) {
                baison_app.api.toast({msg: $rootScope.language.MSG_YOU_HAVE_USE_CARDS}); //'您已经使用过储值卡了!'
                return;
            }


            if ($scope.activecheckclass['005'] == 'disable') {
                return;
            }

            $scope.vipczkData = {};
            check_window = ngDialog.open({closeByDocument: false,
                trapFocus: false,
                template: './html/cashier/dialog/check_005_vipczk.html',
                disableAnimation: true,
                scope: $scope,
                preCloseCallback: function () {
                    $scope.open_windows.pop();
                },
                controller: ['$scope', '$rootScope', function ($scope, $rootScope) {
                        var current_vip = $rootScope.goods_cart.vip;
                        if (current_vip.vip_code != '') {
                            $scope.vipczkData.vipCode = '';
                            //接口获取一人多卡信息(根据手机号)
                            Cards.getCards_by_code(current_vip.tel).then(function (response) {
                                //一人多卡信息
                                if (response.data.status == 1) {
                                    $scope.czkCardsGroup = response.data.data;
                                }
                            });
                        }
                        //模拟一组假数据：多张储值卡信息
//                      $scope.czkCardsGroup = [{'czk': 111111}, {'czk': 222222}, {'czk': 333333}, {'czk': 444444}, {'czk': 555555}];
                        //实付金额
                        $scope.vipczkData.payMoney = '';
                        //密码
                        $scope.vipczkData.password = '';
                        //输入储值卡号，查询储值卡金额
                        $scope.check_vipczk_input = function (password, code) {

                            var re = /^[0-9]+[0-9]*$/;
                            if (!re.test(code)) {
                                baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_ENTER_AMOUNT_ACTULLT_PAID}); //'请输入一个有效的储值卡卡号'
                                $scope.vipczkData.vipCode = '';
                                return;
                            }
                            //如果当前是会员，假设就一张储值卡         
                            if (code == '') {
                                baison_app.api.toast({msg: $rootScope.language.MSG_PLI_INPUT_SAVING_CARD_CODE}); //'请输入储值卡号'
                                return;
                            } else {
                                //储值卡卡号
                                Cards.cardsNo_search(code, password).then(function (response) {
                                    if (response.data.status == 1) {
                                        $scope.vipczkData.money = response.data.data.dqje; //储值卡余额
                                    } else {
                                        baison_app.api.toast({msg: $rootScope.language.MSG_CANT_FOUND_RESULT}); //'没有查询到结果'
                                    }
                                });
                            }
                        };
                    }]
            });
        };
        $scope.check_005_vipczk_submit = function (payData) {
            //判断付款金额是否大于卡内余额
            if (parseFloat(payData.money) < parseFloat(payData.payMoney)) {
                baison_app.api.toast({msg: $rootScope.language.MSG_LACK_OF_BALANCE}); // '余额不足'
                return;
            }
            //判断付款金额是否大于代付金额
            if (parseFloat(payData.payMoney) > $rootScope.goods_cart.info.daifu_money) {
                payData.payMoney = $rootScope.goods_cart.info.daifu_money;
            }

            //数据整理
            var pay_money, final_money, remark, coupon_code;
            //实付金额：pay_money
            pay_money = parseFloat(payData.payMoney);
            if (payData.payMoney == 0 || payData.payMoney == '') {
                baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_ENTER_AMOUNT_ACTULLT_PAID}); //'请输入实付金额'
                return;
            }

            final_money = (pay_money > $rootScope.goods_cart.info.daifu_money) ? $rootScope.goods_cart.info.daifu_money : pay_money;
            final_money = parseFloat(final_money);
            remark = $rootScope.language.MSG_USE_VALUE_CARD_CONSUMPTION + pay_money; //'使用储值卡,消费'
            coupon_code = pay_money;
            //添加数据
            GoodsCart.add_check('005', getCheckName('005'), pay_money, final_money, coupon_code, remark);
            $scope.submitDisable = !GoodsCart.is_pay_over();
            set_checkclass();
            ngDialog.close(check_window);
//            $scope.open_windows.pop();
        };
        //支付宝 微信 支付方式 支付完成处理逻辑
        $scope.payable = [];
        //判断是否需退款
        var wx_zfb_is_cancle_pay = function (record_code) {
            for (var i = 0; i < $scope.payable.length; i++) {
                if ($scope.payable[i].record_code == record_code) {
                    return 1;
                }
            }
            return 0;
        };
        //判断是否已支付
        var wx_zfb_is_pay = function (trade_no) {
            for (var i = 0; i < $scope.payable.length; i++) {
                if ($scope.payable[i].trade_no == trade_no) {
                    return 1;
                }
            }
            return 0;
        };
        var wx_zfb_pay_over = function (payData, record_code) {
            //数据整理
            var pay_money, final_money, remark, coupon_code;
            final_money = pay_money = parseFloat(payData.money);
            if (pay_money == 0 || pay_money == null || pay_money == undefined || pay_money == '') {
                ngDialog.close(check_window);
                return;
            }
            remark = $rootScope.language.MSG_TRANSATION_SERIAL_NUMBER + payData.transactionid; //'交易流水号：'
            coupon_code = payData.transactionid; //TODO 此处应该交易流水号
            checkname = payData.CheckName;
            describename = payData.DescribeName;
            //var openid = payData.openid;
            //添加数据
            GoodsCart.add_check(describename, checkname, pay_money, final_money, coupon_code, remark);
            //支付完毕状态检测
            GoodsCart.is_pay_over();
            //
            $scope.payable.push({'trade_no': coupon_code, 'record_code': record_code, 'total_fee': pay_money});
            set_checkclass();
            ngDialog.close(check_window);
            if ($rootScope.goods_cart.info.daifu_money == 0) {
                //直接结算收银
                $scope.submit_click();
            }

        };
        //微信
        var weixin_saoma_window = '';
        //查询状态定时器
        var weixin_saoma_status_timer = '';
        //查询超时定时器
        var weixin_saoma_over_timer = '';
        //微信退款
        var wx_cancel_trade = function () {
            var param = {};
            param.record_code = $rootScope.goods_cart.record_code;
            WeiXin_ZF.weixin_cancel_trade(param);
        };
        //微信扫码 ------------------------------------------------
        var check_008_weixinsaoma = function () {
            //冲突检测
            if (GoodsCart.has_check(['008'])) {
                baison_app.api.toast({msg: $rootScope.language.MSG_YOU_HAVE_USE_VX_SAOMA_CASHIER}); //'您已经使用过微信扫码收银了!'
                return;
            }

            if ($scope.activecheckclass['008'] == 'disable') {
                return;
            }

            $scope.weixinsaomaData = {};
            $scope.weixinsaomaData.money = parseFloat($rootScope.goods_cart.info.daifu_money).toFixed(2);
            check_window = ngDialog.open({closeByDocument: false,
                trapFocus: false,
                template: './html/cashier/dialog/check_008_weixinsaoma.html',
                disableAnimation: true,
                scope: $scope,
                showClose: false,
                preCloseCallback: function () {
                    $scope.open_windows.pop();
                },
                controller: ['$scope', '$rootScope', function ($scope, $rootScope) {
                        ////根据api提交扫码信息
                        weixinsaoma_src_png();
                    }]
            });

            weixin_saoma_status_timer = setInterval(function () {
				if($rootScope.goods_cart.third_settle_status[$rootScope.goods_cart.record_code] == 1 ){
                    clearInterval(weixin_saoma_status_timer);
                    clearTimeout(weixin_saoma_over_timer);
					return;
				}
                var param = {};
                param.record_code = $rootScope.goods_cart.record_code;
                //根据api查询付款信息
                WeiXin_ZF.weixin_orderquery(param).then(function (ret) {
                    //baison_app.api.alert({msg:ret,title:'ret'});
                    if (1 == ret.data.status) {
						$rootScope.goods_cart.third_settle_status[$rootScope.goods_cart.record_code] = 1;
                        clearInterval(weixin_saoma_status_timer);
                        clearTimeout(weixin_saoma_over_timer);
                        if (wx_zfb_is_pay(ret.data.data.transaction_id) == 1) {
                            return;
                        }
                        //付款逻辑操作
                        var payData = {};
                        payData.money = parseFloat(ret.data.data.total_fee / 100);
                        payData.transactionid = ret.data.data.transaction_id;
                        payData.CheckName = getCheckName('008');
                        payData.DescribeName = '008';
                        //payData.openid = ret.data.data.openid;
                        wx_zfb_pay_over(payData, $rootScope.goods_cart.record_code);
                    } else {
                        if (ret.data.data == undefined || ret.data.data == null) {
                            return;
                        }
                        switch (ret.data.data.trade_state) {
                            case 'REFUND':
                            {
                                baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_TO_REFUND}); //'转入退款！'
                                break;
                            }
                            case 'NOTPAY':
                            {
                                baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_NOT_PAY}); //'未支付！'
                                break;
                            }
                            case 'CLOSED':
                            {
                                baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_HAS_BEEN_SHUT_DOWN}); //'已关闭！'
                                break;
                            }
                            case 'REVOKED':
                            {
                                baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_HAD_WITHDRAWN}); //'已撤销！'
                                break;
                            }
                            case 'USERPAYING':
                            {
                                baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_USER_PAY_NOW}); //'用户支付中！'
                                break;
                            }
                            case 'PAYERROR':
                            {
                                baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_PAY_FAIL_BANK_RETURN_FAIL}); //'支付失败！银行返回失败'
                                break;
                            }
                        }
                    }

//                    }
//                    }
                });
            }, 5000);
            //1分钟后关闭查询
            weixin_saoma_over_timer = setTimeout(function () {
                clearInterval(weixin_saoma_status_timer);
                if (wx_zfb_is_cancle_pay($rootScope.goods_cart.record_code) == 1) {
                    return;
                }
                baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_PAY_OVER_TIME}); //'支付超时！'
                //wx_cancel_trade();
                ngDialog.close(check_window);
            }, 3*60000);
        };
        //显示扫描图片
        var weixinsaoma_src_png = function () {
            //传递给微信的购物车商品名称

            var goods_name = '';
            $.each($rootScope.goods_cart.list, function (i, n) {
                goods_name = goods_name + n.GoodsName + ' [' + n.SkuPropertyName + '];';
            });
            var param = {};
            param.record_code = $rootScope.goods_cart.record_code;
            param.body = goods_name;
            //TODO 金额单位为元
            param.total_fee = parseFloat($scope.weixinsaomaData.money * 100).toFixed(2);
            param.activity = 1;
            param.shop_guide = "BaCode:"+$rootScope.goods_cart.list[0].daogou+";CounterCode:"+$rootScope.current_shop.ShopCode;
            ////根据api提交扫码信息 retapiService('weixin/weixin/scan_pay_2',param)
            WeiXin_ZF.weixin_scan_pay(param).then(function (ret) {
                var record_code = new Date().getTime(); //$rootScope.goods_cart.record_code;
                var src = 'file://' + baison_app.api.fsDir + '/barImage/' + record_code + '.png';
                //baison_app.api.alert({msg:ret});
                if (1 == ret.data.status) {
                    //TODO 此处二维码可以定期删除
                    var qr_str = ret.data.data;
                    baison_app.scanner.encode({
                        string: qr_str,
                        save: {
                            imgPath: "fs://barImage",
                            imgName: record_code + ".png"
                        }
                    }, function (ret, err) {
                        if (ret.status) {
                            $scope.weixinsaomaData.src = src;
                            $rootScope.goods_cart.src_code = record_code;
                            baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_QR_CODE_GENERATED_SUCCEED}); //'生成二维码成功'
                        } else {

                            baison_app.api.toast({msg: err});
                        }
                        baison_app.api.hideProgress();
                    });
                } else {
                    baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_NETWORK_ABNORMAL}); //'网络异常！'
                    baison_app.api.hideProgress();
                }
            });
        };
        //输入付款金额确定
        $scope.check_weixinsaoma_input = function () {
            delete $scope.weixinsaomaData.src;
            var integral = $scope.weixinsaomaData.money;
            var re = /^([0-9]\d*.\d*|[0-9]\d*)$/;
            if (integral != undefined && integral != null && integral != '' && integral != 0) {
                if (!re.test(integral)) {
                    baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_INPUT_VALID_AMOUNT}); //'请输入一个有效的金额'
                    $scope.weixinsaomaData.money = '';
                    return;
                }
            } else {

                baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_INPUT_VALID_AMOUNT}); //'请输入一个有效的金额'
                return;
            }

            if ($scope.weixinsaomaData.money > $rootScope.goods_cart.info.daifu_money) {
                $scope.weixinsaomaData.money = parseFloat($rootScope.goods_cart.info.daifu_money).toFixed(2);
            }
            baison_app.api.showProgress({
                title: $rootScope.language.MSG_GENERATED_IN_THER_QR_CODE,
                modal: false
            }); //'生成二维码中...'
            var record_code = $rootScope.goods_cart.src_code;
            var src = 'file://' + baison_app.api.fsDir + '/barImage/' + record_code + '.png';
            baison_app.fs.remove({
                path: src
            }, function (ret, err) {
                weixinsaoma_src_png();
            });
        };
        //关闭微信扫码对话框
        $scope.weixin_saoma_window_close = function () {
            clearInterval(weixin_saoma_status_timer);
            clearTimeout(weixin_saoma_over_timer);
            //wx_cancel_trade();
            ngDialog.close(check_window);
        };

        //暂时去掉了
        $scope.check_008_weixinsaoma_submit = function (payData) {
            var payData = {};
            payData.money = $rootScope.goods_cart.info.daifu_money;
            payData.CheckName = getCheckName('008');
            payData.DescribeName = '008';
            wx_zfb_pay_over(payData);
        };
        //微信刷卡 ------------------------------------------------
        var weixin_tiaoma_window = '';
        //查询状态定时器
        var weixin_tiaoma_status_timer = '';
        //查询超时定时器
        var weixin_tiaoma_over_timer = '';


        var check_010_weixinshuaka = function () {
            //冲突检测
            if (GoodsCart.has_check(['010'])) {
                baison_app.api.toast({msg: $rootScope.language.MSG_YOU_HAVE_USE_WECHART_CASHIER}); //'您已经使用过微信刷卡收银了!'
                return;
            }

            if ($scope.activecheckclass['010'] == 'disable') {
                return;
            }

            $scope.weixinshuakaData = {};
            $scope.weixinshuakaData.money = parseFloat($rootScope.goods_cart.info.daifu_money).toFixed(2);
            check_window = ngDialog.open({closeByDocument: false,
                trapFocus: true,
                template: './html/cashier/dialog/check_010_weixinshuaka.html',
                disableAnimation: true,
                scope: $scope,
                showClose: false,
                preCloseCallback: function () {
                    $scope.open_windows.pop();
                },
            });
			$scope.focus("wxsk", 1);
            $scope.type = 'wxsk';
        };
        $scope.check_010_weixinshuaka_submit = function () {
            var integral = $scope.weixinshuakaData.money;
            var re = /^([0-9]\d*.\d*|[0-9]\d*)$/;
            if (integral != undefined && integral != null && integral != '' && integral != 0) {
                if (!re.test(integral)) {
                    baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_INPUT_VALID_AMOUNT}); //'请输入一个有效的金额'
                    $scope.weixinshuakaData.money = '';
                    return;
                }
            } else {
                baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_INPUT_VALID_AMOUNT}); //'请输入一个有效的金额'
                return;
            }
            if ($scope.weixinshuakaData.money > $rootScope.goods_cart.info.daifu_money) {
                $scope.weixinshuakaData.money = parseFloat($rootScope.goods_cart.info.daifu_money).toFixed(2);
            }
            //微信钱包号码
            var auth_code = $scope.weixinshuakaData.auth_code;
            if (auth_code == undefined || auth_code == null) {
                return baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_ENTER_PAY_CODE}); //'请输入支付码'
            }
            var re = /^[1-9]+[0-9]*$/;
            if (!re.test(auth_code)) {
                baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_ENTER_VALID_PAYMENT_CODE}); //'请输入一个有效的支付码'
                $scope.weixinshuakaData.auth_code = '';
                return;
            }

            //传递给微信的购物车商品名称

            var goods_name = '';
            $.each($rootScope.goods_cart.list, function (i, n) {
                goods_name = goods_name + n.GoodsName + ' [' + n.SkuPropertyName + '];';
            });
            //购买商品记录号
            var record_code = $rootScope.goods_cart.record_code;
            var data = {
                record_code: record_code,
                daifu: parseFloat($scope.weixinshuakaData.money * 100).toFixed(2),
                auth_code: auth_code,
                body: goods_name,
                activity : 1,
                shop_guide :"BaCode:"+$rootScope.goods_cart.list[0].daogou+";CounterCode:"+$rootScope.current_shop.ShopCode
            };
            //点一下确定就关闭
            ngDialog.close(check_window);
//            $scope.open_windows.pop();
            // 根据api提交微信钱包信息
            WeiXin_ZF.weixin_tiaoma_trade(data).then(function (ret) {
                //baison_app.api.alert({msg:ret,title:'ret'});

                //查询状态定时器
                var weixin_tiaoma_status_timer = '';
                //查询超时定时器
                var weixin_tiaoma_over_timer = '';
                weixin_tiaoma_status_timer = setInterval(function () {
					if($rootScope.goods_cart.third_settle_status[$rootScope.goods_cart.record_code] == 1 ){
						clearInterval(weixin_tiaoma_status_timer);
                        clearTimeout(weixin_tiaoma_over_timer);
                        return;
					}
                    var param = {};
                    param.record_code = $rootScope.goods_cart.record_code;
                    //根据api查询付款信息
                    WeiXin_ZF.weixin_orderquery(param).then(function (ret) {

                        //baison_app.api.alert({msg:ret,title:'ret'});
                        if (1 == ret.data.status) {
							$rootScope.goods_cart.third_settle_status[$rootScope.goods_cart.record_code] = 1;
                            clearInterval(weixin_tiaoma_status_timer);
                            clearTimeout(weixin_tiaoma_over_timer);
                            if (wx_zfb_is_pay(ret.data.data.transaction_id) == 1) {
                                return;
                            }
                            //付款逻辑操作
                            var payData = {};
                            payData.money = parseFloat(ret.data.data.total_fee / 100);
                            payData.transactionid = ret.data.data.transaction_id;
                            payData.CheckName = getCheckName('010');
                            payData.DescribeName = '010';
                            wx_zfb_pay_over(payData, $rootScope.goods_cart.record_code);
                        } else {
                            if (ret.data.data == undefined || ret.data.data == null) {
                                return;
                            }
                            switch (ret.data.data.trade_state) {
                                case 'REFUND':
                                {
                                    baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_TO_REFUND}); //'转入退款！'
                                    break;
                                }
                                case 'NOTPAY':
                                {
                                    baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_NOT_PAY}); //'未支付！'
                                    break;
                                }
                                case 'CLOSED':
                                {
                                    baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_HAS_BEEN_SHUT_DOWN}); //'已关闭！'
                                    break;
                                }
                                case 'REVOKED':
                                {
                                    baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_HAD_WITHDRAWN}); //'已撤销！'
                                    break;
                                }
                                case 'USERPAYING':
                                {
                                    baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_USER_PAY_NOW}); //'用户支付中！'
                                    break;
                                }
                                case 'PAYERROR':
                                {
                                    baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_PAY_FAIL_BANK_RETURN_FAIL}); //'支付失败！银行返回失败'
                                    break;
                                }
                            }
                        }

                    });
                }, 5000);
                //1分钟后关闭查询
                weixin_tiaoma_over_timer = setTimeout(function () {
                    clearInterval(weixin_tiaoma_status_timer);
                    if (wx_zfb_is_cancle_pay($rootScope.goods_cart.record_code) == 1) {
                        return;
                    }
                    baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_PAY_OVER_TIME}); //'支付超时！'
                    //wx_cancel_trade();
                    ngDialog.close(check_window);
                }, 3*60000);

            });
        };

        //关闭微信条码对话框
        $scope.weixin_tiaoma_window_close = function () {
            clearInterval(weixin_tiaoma_status_timer);
            clearTimeout(weixin_tiaoma_over_timer);
            //wx_cancel_trade();
            ngDialog.close(check_window);
        };
        //支付宝支付
        var zhifubao_saoma_window = '';
        //查询状态定时器
        var zhifubao_saoma_status_timer = '';
        //查询超时定时器
        var zhifubao_saoma_over_timer = '';



        //支付宝撤销订单
        var zfb_cancel_trade = function () {
            var param = {};
            param.out_trade_no = $rootScope.goods_cart.record_code;
            ZhiFuBao_ZF.ordercancel(param).then(function (ret) {
                var msg = ret.data.message;
                if (1 == ret.data.status) {
                    sg = ret.data.message;
                    baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: ret.data.msg});
                } else {
                    msg = ret.data.message;
                    baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: ret.msg});
                }
            });
        };
        //显示扫码图片（支付宝）
        var zhifubaosaoma_src_png = function () {
            var param = {};
            param.out_trade_no = $rootScope.goods_cart.record_code; //商品订单号
            param.total_amount = parseFloat($scope.zhifubaosaomaData.money).toFixed(2); //支付金额
            param.undiscountable_amount = parseFloat($scope.zhifubaosaomaData.money).toFixed(2); //暂时不可打折
            param.subject = $rootScope.language.MSG_SWEEP_PAY; //订单标题   "扫码支付"
            var goods_name = '';
            $.each($rootScope.goods_cart.list, function (i, n) {
                goods_name = goods_name + n.GoodsName + ' [' + n.SkuPropertyName + '];';
            });
            param.body = goods_name; //订单描述
            param.time_expire = 60000; //支付超时时间点
            
            // operator_id	 String	可选	28	商户操作员编号	yx_001
            // store_id	 String	可选	32	商户门店编号	NJ_001
            // terminal_id	 String	可选	32	商户机具终端编号	NJ_T_001
            
            param.operator_id = $rootScope.goods_cart.list[0].daogou;//$rootScope.user.UserCode;//商户操作员编号
            param.store_id = $rootScope.current_shop.ShopCode;//商户门店编号
            param.terminal_id = baison_app.api.deviceId.toString();//商户机具终端编号
            
            ZhiFuBao_ZF.saoma_scan_pay(param).then(function (ret) {
                var record_code = new Date().getTime(); //var record_code = $rootScope.goods_cart.record_code;
                var src = 'file://' + baison_app.api.fsDir + '/barImage/' + record_code + '.png';
                if (1 == ret.data.status) {

                    var qr_str = ret.data.qr_code;
                    baison_app.scanner.encode({
                        string: qr_str,
                        save: {
                            imgPath: "fs://barImage",
                            imgName: record_code + ".png"
                        }
                    }, function (ret, err) {
                        if (ret.status) {
                            $scope.zhifubaosaomaData.src = src;
                            $rootScope.goods_cart.src_code = record_code;
                            baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_QR_CODE_GENERATED_SUCCEED}); //'生成二维码成功'
                        } else {
                            baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: err});
                        }
                        baison_app.api.hideProgress();
                    });
                } else {
                    baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_NETWORK_ABNORMAL}); //'网络异常！'
                    baison_app.api.hideProgress();
                }
            });
        };
        //输入付款金额确定
        $scope.check_zhifubaosaoma_input = function () {
            delete $scope.zhifubaosaomaData.src;
            var integral = $scope.zhifubaosaomaData.money;
            var re = /^([0-9]\d*.\d*|[0-9]\d*)$/;
            if (integral != undefined && integral != null && integral != '' && integral != 0) {
                if (!re.test(integral)) {
                    baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_INPUT_VALID_AMOUNT}); //'请输入一个有效的金额'
                    $scope.zhifubaosaomaData.money = '';
                    return;
                }
            } else {
                baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_INPUT_VALID_AMOUNT}); //'请输入一个有效的金额'
                return;
            }
            if ($scope.zhifubaosaomaData.money > $rootScope.goods_cart.info.daifu_money) {
                $scope.zhifubaosaomaData.money = parseFloat($rootScope.goods_cart.info.daifu_money).toFixed(2);
            }
            baison_app.api.showProgress({
                title: $rootScope.language.MSG_GENERATED_IN_THER_QR_CODE,
                modal: false
            }); //'生成二维码中...'
            var record_code = $rootScope.goods_cart.src_code;
            var src = 'file://' + baison_app.api.fsDir + '/barImage/' + record_code + '.png';
            baison_app.fs.remove({
                path: src
            }, function (ret, err) {
                zhifubaosaoma_src_png();
            });
        };
        //支付宝扫码
        var check_009_zhifubaosaoma = function () {
            //冲突检测
            if (GoodsCart.has_check(['009'])) {
                baison_app.api.toast({msg: $rootScope.language.MSG_YOU_HAVE_USE_ZHIFUBAO_QR_CASHIER}); //'您已经使用过支付宝扫码收银了!'
                return;
            }

            if ($scope.activecheckclass['009'] == 'disable') {
                return;
            }

            $scope.zhifubaosaomaData = {};
            $scope.zhifubaosaomaData.money = parseFloat($rootScope.goods_cart.info.daifu_money).toFixed(2);
            check_window = ngDialog.open({closeByDocument: false,
                trapFocus: false,
                template: './html/cashier/dialog/check_009_zhifubaosaoma.html',
                disableAnimation: true,
                scope: $scope,
                showClose: false,
                preCloseCallback: function () {
                    $scope.open_windows.pop();
                },
                controller: ['$scope', '$rootScope', function ($scope, $rootScope) {
                        ////根据api提交扫码信息
                        zhifubaosaoma_src_png();
                    }]
            });
            //查询状态定时器
            var zhifubao_saoma_status_timer = '';
            //查询超时定时器
            var zhifubao_saoma_over_timer = '';
            zhifubao_saoma_status_timer = setInterval(function () {
				if($rootScope.goods_cart.third_settle_status[$rootScope.goods_cart.record_code] == 1 ){
                    clearInterval(zhifubao_saoma_status_timer);
                    clearTimeout(zhifubao_saoma_over_timer);
					return;
				}
                var param = {};
                param.out_trade_no = $rootScope.goods_cart.record_code;
                //根据api查询付款信息
                ZhiFuBao_ZF.orderquery(param).then(function (ret) {
                    //ret 返回的参数如下
                    //trade_no//out_trade_no//open_id//buyer_logon_id//trade_status//total_amount
                    if (1 == ret.data.status) {
						$rootScope.goods_cart.third_settle_status[$rootScope.goods_cart.record_code] = 1;
                        clearInterval(zhifubao_saoma_status_timer);
                        clearTimeout(zhifubao_saoma_over_timer);
                        if (wx_zfb_is_pay(ret.data.trade_no) == 1) {
                            return;
                        }
                        //付款逻辑操作
                        var payData = {};
                        payData.money = ret.data.buyer_pay_amount;
                        payData.transactionid = ret.data.trade_no;
                        payData.CheckName = getCheckName('009');
                        payData.DescribeName = '009';
                        wx_zfb_pay_over(payData, $rootScope.goods_cart.record_code);
                    }
                });
            }, 5000);
            //1分钟后关闭查询
            zhifubao_saoma_over_timer = setTimeout(function () {
                clearInterval(zhifubao_saoma_status_timer);
                if (wx_zfb_is_cancle_pay($rootScope.goods_cart.record_code) == 1) {
                    return;
                }
                baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_PAY_OVER_TIME}); //'支付超时！'
                ngDialog.close(check_window);
                //防止 意外 执行下退款操作
                //zfb_cancel_trade();
            }, 3*60000);
        };

        //关闭支付宝扫码对话框
        $scope.zhifubao_saoma_window_close = function () {
            clearInterval(zhifubao_saoma_status_timer);
            clearTimeout(zhifubao_saoma_over_timer);
            //zfb_cancel_trade();
            ngDialog.close(check_window);
        };
        var zhifubao_tiaoma_window = '';
        //查询状态定时器
        var zhifubao_tiaoma_status_timer = '';
        //查询超时定时器
        var zhifubao_tiaoma_over_timer = '';

        var check_011_zhifubaotiaoma = function () {
            //冲突检测
            if (GoodsCart.has_check(['011'])) {
                baison_app.api.toast({msg: $rootScope.language.MSG_YOU_HAVE_USE_WECHART_CASHIER}); //'您已经使用过微信刷卡收银了!'
                return;
            }

            if ($scope.activecheckclass['011'] == 'disable') {
                return;
            }

            $scope.zhifubaotiaomaData = {};
            $scope.zhifubaotiaomaData.money = parseFloat($rootScope.goods_cart.info.daifu_money).toFixed(2);
            check_window = ngDialog.open({closeByDocument: false,
                trapFocus: true,
                template: './html/cashier/dialog/check_011_zhifubaotiaoma.html',
                disableAnimation: true,
                scope: $scope,
                showClose: false,
                preCloseCallback: function () {
                    $scope.open_windows.pop();
                },
            });
			$scope.focus("zfbsk", 1);
            $scope.type = 'zfbsk';
        };
        $scope.check_011_zhifubaotiaoma_submit = function () {
            //微信钱包号码
            var auth_code = $scope.zhifubaotiaomaData.auth_code;
            var integral = $scope.zhifubaotiaomaData.money;
            var re = /^([0-9]\d*.\d*|[0-9]\d*)$/;
            if (integral != undefined && integral != null && integral != '' && integral != 0) {
                if (!re.test(integral)) {
                    baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_INPUT_VALID_AMOUNT}); //'请输入一个有效的金额'
                    $scope.zhifubaotiaomaData.money = '';
                    return;
                }
            } else {
                baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_INPUT_VALID_AMOUNT}); //'请输入一个有效的金额'
                return;
            }
            if ($scope.zhifubaotiaomaData.money > $rootScope.goods_cart.info.daifu_money) {
                $scope.zhifubaotiaomaData.money = parseFloat($rootScope.goods_cart.info.daifu_money).toFixed(2);
            }
            //微信钱包号码
            var auth_code = $scope.zhifubaotiaomaData.auth_code;
            if (auth_code == undefined || auth_code == null) {
                return baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_ENTER_PAY_CODE}); //'请输入支付码'
            }
            var re = /^[1-9]+[0-9]*$/;
            if (!re.test(auth_code)) {
                baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_ENTER_VALID_PAYMENT_CODE}); //'请输入一个有效的支付码'
                $scope.zhifubaotiaomaData.auth_code = '';
                return;
            }
            var param = {};
            param.out_trade_no = $rootScope.goods_cart.record_code; //商品订单号
            param.total_amount = parseFloat($scope.zhifubaotiaomaData.money).toFixed(2); //支付金额
            param.undiscountable_amount = parseFloat($scope.zhifubaotiaomaData.money).toFixed(2); //暂时不可打折
            param.auth_code = auth_code;
            param.subject = $rootScope.language.MSG_BAR_CODE_TO_PAY; //"条码支付"//订单标题
            var goods_name = '';
            $.each($rootScope.goods_cart.list, function (i, n) {
                goods_name = goods_name + n.GoodsName + ' [' + n.SkuPropertyName + '];';
            });
            param.body = goods_name; //订单描述
            
            param.operator_id = $rootScope.goods_cart.list[0].daogou;//$rootScope.user.UserCode;//商户操作员编号
            param.store_id = $rootScope.current_shop.ShopCode;//商户门店编号
            param.terminal_id = baison_app.api.deviceId.toString();//商户机具终端编号
            
            
            // 根据api提交微信钱包信息
            ngDialog.close(check_window);
//            $scope.open_windows.pop();
            ZhiFuBao_ZF.tiaoma_pay(param).then(function (ret) {
                //ret返回参数如下
                //trade_no//out_trade_no//open_id//buyer_logon_id//total_amount//receipt_amount//
                //invoice_amount//buyer_pay_amount//point_amount//gmt_payment//fund_bill_list//
                //store_name(不是必返回)
                //status 为 1 时 交易处理成功

                //5秒后再次检查订单支付状态
                zhifubao_tiaoma_status_timer = setInterval(function () {
					if($rootScope.goods_cart.third_settle_status[$rootScope.goods_cart.record_code] == 1 ){
						clearInterval(zhifubao_tiaoma_status_timer);
                        clearTimeout(zhifubao_tiaoma_over_timer);
                        return;
					}
                    var param = {};
                    param.out_trade_no = $rootScope.goods_cart.record_code;
                    // 根据api查询付款信息
                    ZhiFuBao_ZF.orderquery(param).then(function (ret) {

                        if (1 == ret.data.status) {
							$rootScope.goods_cart.third_settle_status[$rootScope.goods_cart.record_code] = 1;
                            clearInterval(zhifubao_tiaoma_status_timer);
                            clearTimeout(zhifubao_tiaoma_over_timer);
                            if (wx_zfb_is_pay(ret.data.trade_no) == 1) {
                                return;
                            }
                            //付款逻辑操作
                            var payData = {};
                            payData.money = ret.data.buyer_pay_amount;
                            payData.transactionid = ret.data.trade_no;
                            payData.CheckName = getCheckName('011');
                            payData.DescribeName = '011';
                            wx_zfb_pay_over(payData, $rootScope.goods_cart.record_code);
                        }
//                          else {
//                              //在线支付失败
//                              var err_msg = ret.data.message + ret.data.sub_code;
//                              baison_app.api.toast({msg: '支付失败！' + err_msg + ' 5秒钟后再次查询'});
//                          }
                    });
                }, 5000);
                //1分钟后关闭查询
                zhifubao_tiaoma_over_timer = setTimeout(function () {
                    clearInterval(zhifubao_tiaoma_status_timer);
                    if (wx_zfb_is_cancle_pay($rootScope.goods_cart.record_code) == 1) {
                        return;
                    }
                    baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_PAY_OVER_TIME}); //'支付超时！'
                    ngDialog.close(check_window);
                    //防止 意外 执行下退款操作
                    //zfb_cancel_trade();
                }, 3*60000);


            });
        };
        //关闭支付宝条码对话框
        $scope.zhifubao_tiaoma_window_close = function () {
            clearInterval(zhifubao_tiaoma_status_timer);
            clearTimeout(zhifubao_tiaoma_over_timer);
            //zfb_cancel_trade();
            ngDialog.close(check_window);
        };


        //订金收银
        var check_013_djsy = function () {
            //冲突检测
            if (GoodsCart.has_check(['013'])) {
                baison_app.api.toast({msg: $rootScope.language.MSG_YOU_HAVE_USE_DEPOSIT}); //'您已经使用过储值卡了!'
                return;
            }
            if ($scope.activecheckclass['013'] == 'disable') {
                return;
            }
            check_window = ngDialog.open({
                trapFocus: false,
                template: './html/cashier/dialog/check_013_djsy.html',
                disableAnimation: true,
                scope: $scope,
                preCloseCallback: function () {
                    $scope.open_windows.pop();
                },
                controller: ['$scope', '$rootScope', function ($scope, $rootScope) {
                        $scope.depositData = {};
                        $scope.depositData.record_code = '';
                        //输入定金单号，查询定金单金额
                        $scope.check_djdh_input = function (record_code) {
                            //根据订金单号去查询单号的详细信息
                            ServiceOrder.get_record_detail_by_record_code({record_code: record_code}).then(function (response) {
                                if (response.data.status == 1) {
                                    //循环商品定金单中的商品数据
                                    $scope.depositData.remark = [];
                                    $scope.remark = " ";
                                    $.each(response.data.data.goods_detail, function (i, n) {
                                        $.each($rootScope.goods_cart.list, function (index, good) {
                                            if (n.GoodsCode != good.GoodsCode) {
                                                $scope.remark = "true";
                                                $scope.depositData.remark.push({
                                                    'remark': '订购商品：' + '商品货号：' + n.GoodsCode + '商品名字：' + n.GoodsName + '颜色名称：' + n.ColorName + '尺寸名称：' + n.SizeName + '数量：' + n.num
                                                });
                                            }
                                        });
                                    });
                                    $scope.depositData = response.data.data;
                                    //定金单单号
                                    $scope.depositData.record_code = response.data.data.record.record_code;
                                    //订金金额
                                    $scope.depositData.deposit = response.data.data.record.deposit;
                                    //支付金额
                                    $scope.depositData.payMoney = $rootScope.goods_cart.info.daifu_money;
                                    //找零金额
                                    if ($rootScope.goods_cart.info.daifu_money > $scope.depositData.deposit) {
                                        $scope.depositData.changeMoney = 0.0;
                                    } else {
                                        var money = (parseFloat($scope.depositData.deposit).toFixed(2)) - (parseFloat($rootScope.goods_cart.info.daifu_money).toFixed(2));
                                        $scope.depositData.changeMoney = parseFloat(money).toFixed(2);

                                    }

                                } else {  //MSG_CANT_FOUND_RESULT
                                    baison_app.api.toast({msg: $rootScope.language.MSG_CANT_FOUND_RESULT});
                                }
                            });
                        };
                    }]
            });
        };
        $scope.check_013_djsy_submit = function (payData) {
//          baison_app.api.alert({title:'支付',msg:payData});
            //用于保存使用顾客定金单的数据
            $rootScope.gkdjd = payData;
            //数据整理
            var pay_money, final_money, remark, coupon_code;
            if (payData.payMoney == 0 || payData.payMoney == '') {
                baison_app.api.toast({msg: $rootScope.language.TIPS_SET_DEPOSIT_MONEY_NOT_O}); //'定金金额不能是0'
                return;
            }
            //实付金额：pay_money
            if (parseFloat(payData.changeMoney) > 0) {
                pay_money = $rootScope.goods_cart.info.daifu_money;  //等于本单金额
            } else if ($rootScope.goods_cart.info.daifu_money > parseFloat(payData.deposit)) {
                pay_money = parseFloat(payData.deposit);  //等于本单金额
            }
            final_money = (pay_money > $rootScope.goods_cart.info.daifu_money) ? $rootScope.goods_cart.info.daifu_money : pay_money;
            final_money = parseFloat(final_money);
            remark = $rootScope.language.TIPS_USE_DEPOSIT_MONEY_CONSUME + pay_money; //'使用订金金额,消费'
            coupon_code = '';
            //添加数据
            GoodsCart.add_check('013', getCheckName('013'), pay_money, final_money, coupon_code, remark);
            $scope.submitDisable = !GoodsCart.is_pay_over();
            set_checkclass();


            ngDialog.close(check_window);
        };


        var check_006_czk = function () {
            baison_app.api.toast({
                msg: $rootScope.language.TIP_INDEX_TODO_MESSAGE
            });
        };
        var check_007_xjk = function () {
            baison_app.api.toast({
                msg: $rootScope.language.TIP_INDEX_TODO_MESSAGE
            });
        };
		
		
		//非凡支付
        var feifanPay_window;
        var check_103_feifanPay = function () {
			var systype = baison_app.api.systemType;
			if(systype != 'android'){
				baison_app.api.toast({msg: $rootScope.language.MSG_FEIFAN_MODULE_NOT_SYS}); //"MSG_FEIFAN_MODULE_NOT_SYS":"只能在android系统上使用",
                return;
				
			}
			var configData = $api.getStorage('configData');
            if (!configData.feifan.switch) {
                baison_app.api.toast({msg: $rootScope.language.MSG_FEIFAN_MODULE_NOT_OPEN}); //模块未开启
                return;
            }
            //冲突检测
            if (GoodsCart.has_check(['103'])) {
                baison_app.api.toast({msg: $rootScope.language.MSG_YOU_HAVE_USE_FEIFAN_PAY});
                return;
            }
            if ($scope.activecheckclass['103'] == 'disable') {
                return;
            }
            $scope.feifanData = {};
            $scope.feifanData.money = parseFloat($rootScope.goods_cart.info.daifu_money).toFixed(2);
            feifanPay_window = ngDialog.open({
                closeByDocument: false,
                trapFocus: false,
                template: './html/cashier/dialog/cashier_dialog_check_014_feifan.html',
                disableAnimation: true,
                scope: $scope,
                showClose: false,
                preCloseCallback: function () {
                    $scope.open_windows.pop();
                }
            });
        };

        $scope.feifanpay_submit = function () {
            var integral = $scope.feifanData.money;
            var re = /^([0-9]\d*.\d*|[0-9]\d*)$/;
            if (!re.test(integral)) {
                baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_INPUT_VALID_AMOUNT}); //'请输入一个有效的金额'
                $scope.feifanData.money = '';
                return;
            }
            if (!baison_app.feifanPay) {
                baison_app.api.toast({msg: $rootScope.language.MSG_FEIFAN_MODULE_NOT_INSTALL}); //'模块未安装'
                return
            }
            var feifan_param = {
                pay_action: "com.wanda.demo.PayActivity",
                extra_order_no: $rootScope.goods_cart.record_code,
                extra_pay_amount: $scope.feifanData.money*100,
                extra_account: "baison001",
                extra_products: []
            };
            $rootScope.goods_cart.list.forEach(function (n) {
                feifan_param.extra_products.push({
                    productId: n.SkuCode,
                    name: n.GoodsName,
                    count: n.num,
                    price: n.BuyPrice*100
                });
            });
            baison_app.feifanPay.payForResult(feifan_param, function (ret, err) {
                /**
                 * 返回的结果
                 * ret={
                 *     extra_pay_result:0,  //支付结果 0:支付成功,1:支付失败,-1取消支付(取消支付时没有下面的字段)
                 *     extra_order_no:LS1607159522552   //传过去的小票单号
                 *     extra_pay_amount:233             //支付金额
                 *     extra_pay_order_no:2452452256    //支付流水号
                 *     extra_pay_account:"wanda123"     //收款账户
                 *     extra_pay_type: 2001            //支付类型
                 * }
                 * */
                //baison_app.api.alert({msg:ret,title:"飞凡支付结果"});
                if (ret.extra_pay_result == -1) {//取消支付
                    baison_app.api.toast({msg: $rootScope.language.TIPS_PAY_CANCEL});
                }
                if (ret.extra_pay_result == 1) {//支付失败
                    baison_app.api.toast({msg: $rootScope.language.TIPS_PAY_FAIL});
                }
                if (ret.extra_pay_result == 0) {//支付成功
                    baison_app.api.toast({msg: $rootScope.language.TIPS_PAY_SUCCESS});
                    var coupon_code = ret.extra_pay_order_no;
                    var pay_money = ret.extra_pay_amount/100;
                    var final_money = ret.extra_pay_amount/100;
                    var pay_type = ret.extra_pay_type;
                    var code = '103_'+pay_type;
                    var remark = $rootScope.language.TIPS_PAY_NO + ':' + coupon_code + ';' + $rootScope.language.TIPS_CASHIER_MONEY + pay_money; //'优惠券：''；面额：'
                    //添加数据
                    GoodsCart.add_check(code, getCheckName('103'), pay_money, final_money, coupon_code, remark);
                    //支付完毕状态检测
                    $scope.submitDisable = !GoodsCart.is_pay_over();
                    set_checkclass();
                    feifanPay_window.close();
                }
            });
            //feifanPay_window.close()
        };
        //飞凡查询主页面
        $scope.feifanpay_search = function(){
        	baison_app.feifanPay.paySetting('',function(ret){
        		if(!ret.setting_pay_result){
        			baison_app.api.toast({msg: "打开失败"});
        		}
        	});
        
        };
        
        $scope.feifanpay_window_close = function () {
            feifanPay_window.close();
        };
		
		
		
        $scope.checkfunction = {
            '001': check_001_xianjin,
            '002': check_002_yinhangka,
            '003': check_003_youhuiquan,
            '004': check_004_jifen,
            '005': check_005_vipczk,
            '006': check_006_czk,
            '007': check_007_xjk,
            '008': check_008_weixinsaoma,
            '009': check_009_zhifubaosaoma,
            '010': check_010_weixinshuaka,
            '011': check_011_zhifubaotiaoma,
            '012': check_012_card,
            '013': check_013_djsy, //订金收银
            '014': check_012_card,
            '015': check_012_card,
            '016': check_012_card,
            '017': check_012_card,
            '018': check_012_card,
            '019': check_012_card,
            '020': check_012_card,
            '021': check_012_card,
            '022': check_012_card,
            '023': check_012_card,
			'024': check_012_card,
            '025': check_012_card,
			'103': check_103_feifanPay,
            'more': check_more_pay,
            'back': check_back_pay,
//            'foreign': check_foreign_pay
        };
        //各收银方式点击按钮
        $scope.select_check = function (CheckCode) {

            //检测是否开启对应支付方式
            for (var p in $scope.checklistData) {
                if ($scope.checklistData[p].CheckCode == CheckCode) {
                    var ture_test = false;
                    break;
                } else {
                    var ture_test = true;
                }
            }
            //根据是否有支付方式判断是否执行支付操作
            if (ture_test) {
                return;
            }

            $scope.open_windows.push('check_type');
            if (GoodsCart.is_pay_over()) {
                baison_app.api.toast({msg: $rootScope.language.MSG_YOU_PAY_COMLETE_PLEASE_CLICK_COFIRM}); //'您已经支付完毕，请点击确认按钮'
                return;
            }
            type_num = CheckCode;
            $scope.checkfunction[CheckCode]();
        };
        //检查是否可以删除消费记录 （支付宝与微信不可删除）
        var is_del_pay_log = function (i) {
            if (($rootScope.goods_cart.checklist[i].coupon_code != '' && $rootScope.goods_cart.checklist[i].code != '004') || $rootScope.goods_cart.checklist[i].code == '003') {
                return 1;
            } else {
                return 0;
            }
        };
        //支付方式关窗
        $scope.close_check_window = function () {
            ngDialog.close(check_window);
//            $scope.open_windows.pop();
        };
        //删除支付方式
        $scope.check_list_remove = function (i) {
            if (is_del_pay_log(i) == 1) {
                baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_COMPLETE_THE_PAY}); //'请完成支付'
                return;
            }
            GoodsCart.delete_from_check(i);
            set_checkclass();
        };
        //pc版删除支付方式
        $scope.delete_check = function (i) {
            if (is_del_pay_log(i) == 1) {
                baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_COMPLETE_THE_PAY}); //'请完成支付'
                return;
            }
            GoodsCart.delete_from_check(i);
            set_checkclass();
        };

        //取消按钮点击
        $scope.cancel_click = function () {
            var length = $rootScope.goods_cart.checklist.length;
            for (var i = 0; i < length; i++) {
                if (is_del_pay_log(i) == 1) {
                    baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_COMPLETE_THE_PAY}); //'请完成支付'
                    return;
                }
            }
//          set_checkclass();
            //收银结算取消时，删除本地单据
            ReceiptRecord.receipt_cancel_local({'record_code': $rootScope.goods_cart.record_code}).then(function (res) {
                //baison_app.api.alert({msg:res})
            });
            $scope.reset_click();
            $location.path('/cashier/index');
        };
        //重置按钮点击
        $scope.reset_click = function () {
            var length = $rootScope.goods_cart.checklist.length;
            for (var i = 0; i < length; i++) {
                if (is_del_pay_log(i) == 1) {
                    baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_COMPLETE_THE_PAY}); //'请完成支付'
                    return;
                }
            }
            GoodsCart.clear_check();
            set_checkclass();
            $scope.submitDisable = !GoodsCart.is_pay_over();
        };
        //收银界面使用优惠券，加入结算记录里
        var settle_use_coupon = function () {
            var now = timeStamp2String(0, 'datetime');
            $.each($rootScope.goods_cart.couponData, function (i, n) {
                n.coupon.coupon_code.forEach(function (data) {
                    //console.log(n);
                    //console.log(parseFloat(n.coupon.rebate) * $rootScope.goods_cart.info.total_money);
                    if (data.is_use || n.coupon.promo_id == '') {
                        var info = {
                            code: '003',
                            name: n.coupon.coupon_name,
                            pay_money: (n.detail.money <= 0) ? ($rootScope.goods_cart.info.total_money - parseFloat(n.coupon.rebate) * $rootScope.goods_cart.info.total_money) : n.detail.money,
                            final_money: (n.detail.money <= 0) ? ($rootScope.goods_cart.info.total_money - parseFloat(n.coupon.rebate) * $rootScope.goods_cart.info.total_money) : n.detail.money,
                            coupon_code: data.code,
                            remark: ''

                        };
                        $rootScope.goods_cart.checklist.push(info);
                    }

                });

            });
        };
        //生成一个订金退款单
        //判断有没有找零金额，一旦有找零金额就生成一张订金退款单
        var add_depositReturnRecord_by_depositRecord = function (payData) { //payMoney
            //回写顾客定金单的使用金额
            var param = {};
            param.record_code = payData.record_code; //订金单号
            param.use_money = payData.payMoney;  //使用金额
            ServiceOrder.update_depositRecord(param);
            //生成订金退款单
            if (parseFloat(payData.changeMoney) > 0) {
                //需要同时生成一张订金退款单,todo
                var param = {};
                param.tel = payData.record.phone;
                param.customer_code = payData.record.customer_code; //顾客代码
                param.UserCode = $rootScope.gkdjd_userCode;  //经手店员:顾客定金单的经手店员
                param.shop_code = payData.record.shop_code;  //店铺代码
                param.date = timeStamp2String(new Date(), 'datetime');    //日期
                param.record_code = payData.record.record_code; //订金单号
                param.balance_money = payData.changeMoney;           //订金余额
                param.return_money = payData.changeMoney;  //退款金额
                param.is_made_person = $rootScope.user.UserName; //payData.record.is_made_person;     //制单人
                param.is_made_time = timeStamp2String(new Date(), 'datetime');     //制单日期
                param.is_sure_person = $rootScope.user.UserName;           //payData.record.is_sure_person  //确认人
                param.is_sure_time = timeStamp2String(new Date(), 'datetime');              //确认日期
                param.address = payData.record.address;   //地址
                //传结算方式和名称
                param.check_code = '000';//现金退款
                param.return_money = payData.changeMoney;//退款金额
                ServiceOrder.add_depositReturnRecord(param).then(function (ret) {
                    if (ret.data.status == 1) {
                        ngDialog.close(check_window);
                        baison_app.api.toast({msg: ret.data.message});
                    } else {
                        baison_app.api.toast({msg: ret.data.message});
                    }
                });
            }
        };

        //确认按钮点击
        $scope.submit_click = function () {
            if (($rootScope.goods_cart.info.daifu_money).toFixed(2) > 0) {
                baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_COMPLETE_THE_PAY_OR_RESET}); //'请先完成支付 或重置支付方式'
                return;
            }
            if ($rootScope.goods_cart.busy != 0 && $rootScope.goods_cart.busy != 2) { 
                baison_app.api.toast({msg: $rootScope.language.MSG_CKEARING_PLZ_WAIT_MOMENT}); //'正在结算，请稍等'
                return;
            }
            if($rootScope.goods_cart.busy == 2){
                baison_app.api.toast({msg: $rootScope.language.MSG_CKEARING_PLZ_WAIT_MOMENT}); //'正在结算，请稍等'
                $rootScope.goods_cart.busy = 1;
            }
            //$scope.busy = 1;
            //收银界面使用优惠券，加入结算记录里
            settle_use_coupon();

            //保存支付信息到本地和服务器
            ReceiptRecord.pay($rootScope.goods_cart.record_code, $rootScope.goods_cart).then(function (success) {
                //当服务器新增小票失败时给出提示
                $rootScope.goods_cart.busy = 0;
                //baison_app.api.alert({msg:success});
                //console.log(JSON.stringify(success));
                if (success.data.status != 1) {
                    baison_app.api.alert({msg: '服务器错误，小票上传失败!'});
                    return;
                }
                
                //baison_app.api.alert({title:'ctrlfff',msg:success});
                //是否自动打印小票
                var configData = $api.getStorage('configData');
				var printNum = parseInt(configData.printData['num'], 10);
                if (configData.printData && configData.printData['check'] != undefined && configData.printData['check'] != null) {
                    var check = configData.printData['check'];
                    if (check != undefined) {
                        if (check == 1) { //是自动打印小票
                            //var record = xp_getinfo();
                            xp_getinfo().then(function(record){
                                if(isNaN(printNum) || printNum < 1)
                                {
                                    printNum = 1;
                                }
                                var execute_print = function(print_index){
                                    if(print_index >= printNum){
                                        return;
                                    }
                                    Print.xp_print('', record).then(function(){
                                        print_index++;
                                        execute_print(print_index);
                                    });
                                };
                                // for(var i =0; i < printNum; ++i)
                                // {
                                //     Print.xp_print('', record);
                                // }
                                execute_print(0);
                                GoodsCart.clear_check();
                                GoodsCart.clear_cart(); 
                            });
                            
                        }else{
                            GoodsCart.clear_check();
                            GoodsCart.clear_cart();
                        }
                    }
                }
                //生成一个订金退款单
                if ($rootScope.gkdjd != '' && $rootScope.gkdjd !== undefined) {
                    //有找零金额生成订金退款单
                    add_depositReturnRecord_by_depositRecord($rootScope.gkdjd);
                }
                //更新存货数量
                ReceiptRecord.update_skunum($rootScope.goods_cart.list, 0);
                baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_PAY_IS_OVER}); //跳转回收银界面'支付结束'
                $location.path('/cashier/index');
                //$scope.busy = 0;
                
            }).catch(function (err) {
                if (err.data == null) {
                    //是否自动打印小票
                    $rootScope.goods_cart.busy = 0;
                    var configData = $api.getStorage('configData');
					var printNum = parseInt(configData.printData['num'], 10);
                    if (configData.printData && configData.printData['check'] != undefined && configData.printData['check'] != null) {
                        var check = configData.printData['check'];
                        if (check != undefined) {
                            if (check == 1) { //是自动打印小票
                                //var record = xp_getinfo();
                                xp_getinfo().then(function(record){
                                    if(isNaN(printNum) || printNum < 1)
                                    {
                                        printNum = 1;
                                    }
                                    var execute_print = function(print_index){
                                        if(print_index >= printNum){
                                            return;
                                        }
                                        Print.xp_print('', record).then(function(){
                                            print_index++;
                                            execute_print(print_index);
                                        });
                                    };
                                    // for(var i =0; i < printNum; ++i)
                                    // {
                                    //     Print.xp_print('', record);
                                    // }
                                    execute_print(0);
                                    GoodsCart.clear_check();
                                    GoodsCart.clear_cart(); 
                                });
                            }else{
                                GoodsCart.clear_check();
                                GoodsCart.clear_cart();
                            }
                        }
                    }
                    baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_NOT_CONNECTED_INTERNET}); //'没有联网'
                    //更新存货数量
                    ReceiptRecord.update_skunum($rootScope.goods_cart.list, 0);
                    $location.path('/cashier/index');
                    //$scope.busy = 0;
                    
                }
            });
        };
        //点击打印小票按钮打印小票
        $scope.btn_print_click = function () {
            if ($rootScope.goods_cart.info.daifu_money == 0) {
                //var record = xp_getinfo();
                xp_getinfo().then(function(record){
                   var configData = $api.getStorage('configData');
				   var printNum = parseInt(configData.printData['num'], 10);
                   if(isNaN(printNum) || printNum < 1)
                   {
                       printNum = 1;
                   }

                   var execute_print = function(print_index){
					    //baison_app.api.alert({msg:print_index,title:'print_index'});
                        if(print_index >= printNum){
                            return;
                        }
                        Print.xp_print('', record).then(function(ret){
							//baison_app.api.alert({msg:ret,title:'ret'});;
                            print_index++;
                            execute_print(print_index);
                        });
                    };
                    // for(var i =0; i < printNum; ++i)
                    // {
                    //     Print.xp_print('', record);
                    // }
                    execute_print(0); 
                });
                    
            } else {
                baison_app.api.toast({msg: $rootScope.language.MSG_YOU_HAVENT_PAY}); //'您还未付款'
            }
        };

//快捷键区域===========================================================
        //f1 -----------------------------------------------------------/
        shortCutAction.handler('/cashier/settle', 'f1', function () {
            $scope.$apply();
            //只能打开一次
            if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
                $scope.select_check('001');
            }
        });
        //f2 -----------------------------------------------------------/
        shortCutAction.handler('/cashier/settle', 'f2', function () {
            $scope.$apply();
            //只能打开一次
            if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
                $scope.select_check('002');
            }
        });
        //f3 -----------------------------------------------------------/
        shortCutAction.handler('/cashier/settle', 'f3', function () {
            $scope.$apply();
            //只能打开一次
            if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
                $scope.select_check('003');
            }
        });
        //f4 -----------------------------------------------------------/
        shortCutAction.handler('/cashier/settle', 'f4', function () {
            $scope.$apply();
            //只能打开一次
            if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
                $scope.select_check('004');
            }
        });
        //f5 -----------------------------------------------------------/
        shortCutAction.handler('/cashier/settle', 'f5', function () {
            $scope.$apply();
            //只能打开一次
            if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
                $scope.select_check('005');
            }
        });
        //f6 -----------------------------------------------------------/
        shortCutAction.handler('/cashier/settle', 'f6', function () {
            $scope.$apply();
            //只能打开一次
            if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
                $scope.select_check('006');
            }
        });
        //f7 -----------------------------------------------------------/
        shortCutAction.handler('/cashier/settle', 'f7', function () {
            $scope.$apply();
            //只能打开一次
            if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
                $scope.select_check('007');
            }
        });
        //f8 -----------------------------------------------------------/
        shortCutAction.handler('/cashier/settle', 'f8', function () {
            $scope.$apply();
            //只能打开一次
            if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
                $scope.select_check('008');
            }
        });
        //f9 -----------------------------------------------------------/
        shortCutAction.handler('/cashier/settle', 'f9', function () {
            $scope.$apply();
            //只能打开一次
            if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
                $scope.select_check('009');
            }
        });
        //f10 -----------------------------------------------------------/
        shortCutAction.handler('/cashier/settle', 'f10', function () {
            $scope.$apply();
            //只能打开一次
            if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
                $scope.select_check('010');
            }
        });
        //f11 -----------------------------------------------------------/
        shortCutAction.handler('/cashier/settle', 'f11', function () {
            $scope.$apply();
            //只能打开一次
            if ($scope.open_windows[$scope.open_windows.length - 1] == 'main') {
                $scope.select_check('011');
            }
        });
        //esc取消交易 ----------------------------------------------------------/
        shortCutAction.handler('/cashier/settle', 'esc', function () {
            $scope.$apply();
            switch ($scope.open_windows[$scope.open_windows.length - 1]) {
                //打开支付方式窗口的esc：关闭当前窗口
                case 'check_type':
                    $scope.close_check_window();
//                    $scope.open_windows.pop();
                    break;
                default:
            }
            $scope.$apply();
        });

        //监听扫描枪输入 ========================================================//
        $scope.saomiaoSwitch = false;
        $scope.saomiaoStart = 0;
        $scope.saomiaoEnd = 0;
        $scope.saomiaoInput = '';
        $scope.saomiaoTimer = null;
        $rootScope.saomiao = function (event) {
            $scope.btn_enter_switch = true;
            //开启扫描并记录扫描开始时间
            if (!$scope.saomiaoSwitch) {
                $scope.saomiaoStart = new Date().getTime();
                $scope.saomiaoInput = '';
            }
            $scope.saomiaoSwitch = true;
            // $scope.allCode += event.keyCode + "|";//测试用
            if (event.keyCode == 13 && $scope.type == 'wxsk') {//回车键时候,输入框获取焦点
                $scope.focus("wxsk");
            }else if(event.keyCode == 13 && $scope.type == 'zfbsk'){
                $scope.focus("zfbsk");
            } else {
                $scope.saomiaoInput = $scope.saomiaoInput + String.fromCharCode(event.keyCode);
            }
            if ($scope.saomiaoTimer) {
                clearTimeout($scope.saomiaoTimer);
                //return;
            }
            $scope.saomiaoTimer = setTimeout(function () {
                $scope.saomiaoSwitch = false;
                $scope.saomiaoEnd = new Date().getTime();
                //3位以上且**毫秒以内认为是扫描枪录入
                if ($scope.saomiaoInput.length > 3 && ($scope.saomiaoEnd - $scope.saomiaoStart) < 800) {
                    $scope.btn_enter_switch = false;
                    $scope.saomiaoHandler($scope.saomiaoInput);
                }

                $scope.saomiaoInput = ''; //扫描内容清空

                $scope.btn_enter_switch = false;
            }, 500);
        };
        $scope.saomiaoHandler = function (input_saomiao) {
            //console.log(input_saomiao + "|||||");
            if($scope.type == 'zfbsk'){
                $scope.zhifubaotiaomaData.auth_code = input_saomiao;
                $scope.check_011_zhifubaotiaoma_submit();
                $scope.zhifubaotiaomaData.auth_code = '';
            }
            if($scope.type == 'wxsk'){
                $scope.weixinshuakaData.auth_code = input_saomiao;
                $scope.check_010_weixinshuaka_submit();
                $scope.weixinshuakaData.auth_code = '';
            }
            
            $scope.$apply();
            $scope.type = '';
        };
        //============================================================================

    }];
/**
 * 退货界面控制器
 * @author jhua.zuo<jhua.zuo@baisonmail.com>
 * @date 2015-11-23
 */
var CashierReturnCtrl = ['$scope', '$rootScope', '$routeParams', '$location', 'ReceiptRecord', 'ngDialog', 'apiService', 'ShopSetCheck', 'checkGetList', 'WeiXin_ZF', 'ZhiFuBao_ZF', 'BaseGoods', 'PosUser', 'ShopSearch', 'commonInterface', '$q', 'dbGetOne', 'Print', function ($scope, $rootScope, $routeParams, $location, ReceiptRecord, ngDialog, apiService, ShopSetCheck, checkGetList, WeiXin_ZF, ZhiFuBao_ZF, BaseGoods, PosUser, ShopSearch, commonInterface, $q, dbGetOne, Print) {
        ShopSetCheck(); //检查店铺是否绑定
        $scope.input_keyword = ''; //界面输入框的内容
        $scope.checklistData = {};
        var confirm_window = 0;
        var is_return = 0; //是否退款
        //确认按钮disable状态
        $scope.submitDisable = true;
        $scope.check_total_return = false; //全部退款按钮点击状态
        $scope.check_total_readonly = false; //是否强制退款

        //获取收银方式列表
        checkGetList.get_list().then(function (response) {
            var result = response.checkType;
            result.forEach(function (n) {
                $scope.checklistData[n.CheckCode] = n;
            });
        });

        $scope.record_info = {}; //待退货的小票主信息
        $scope.record_list = []; //待退货的商品列表
        $scope.payment_list = []; //待退货的支付信息

        $scope.return_info = {money: 0, num: 0}; //已选择的退货退货信息
        $scope.return_list = []; //已选择的退货商品列表

        //重置单据状态 -------------------------------------------------------------
        var reset = function () {
            $scope.check_total_return = false; //全部退款按钮点击状态
            $scope.check_total_readonly = false; //是否强制退款

            $scope.record_info = {}; //待退货的小票主信息
            $scope.record_list = []; //待退货的商品列表
            $scope.payment_list = []; //待退货的支付信息

            $scope.return_info = {money: 0, num: 0}; //已选择的退货退货信息
            $scope.return_list = []; //已选择的退货商品列表
        };
        //判断是否整单退
        var total_return_true = function () {

            if (!$scope.check_total_return) {
                return;
            }
            var all_num = 0;
            $.each($scope.record_list, function (k, v) {

                var val = v.num - v.return_num - v.select_num;
                if (val <= 0) {
                    all_num += parseInt(v.num);
                }
            });
            if (parseInt(all_num) == $scope.record_info.num) {
                baison_app.api.toast({msg: $rootScope.language.MSG_GOODS_BEYOND_LIMIT_OR_NOT_RETURN}); //'本商品已超出退货限额或者不可退！'
                return 1;
            }

            return 0;
        };
        //整单退添加物品逻辑
        var add_to_total_return = function (goods) {
            add_to_return_logic(goods, 1, goods.num);
        };
        //全退或者取消全退 ---------------------------------------------------------
        $scope.total_return = function () {
            //console.log($scope.check_total_readonly);
            if ($scope.check_total_readonly && ($scope.payment_list.length > 1 || $scope.record_info.cut_money > 0)) {
                baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_MIXED_PAY_SHALL_REFUND}); //'混合支付须整单退款'
                return;
            }
            //判断是否整单退
            if (total_return_true() == 1) {
                return;
            }
            $scope.return_info.money = 0;
            $scope.return_info.num = 0;
            $scope.return_list = [];
            $scope.record_list.forEach(function (e, i) {
                $scope.record_list[i].select_num = 0;
            });
            if ($scope.check_total_return) {
                $scope.record_list.forEach(function (goods, i) {
                    //for (var x = 0; x < goods.num; x++) {
                    //$scope.add_to_return(goods);
                    //}
                    add_to_total_return(goods);
                });
                $scope.check_total_readonly = true;
                get_return_money();

            }


        };
        //整单退逻辑
        var total_return_logic = function (record) {

            if ($scope.payment_list.length <= 1 && $scope.record_info.cut_money <= 0) {
                return;
            }

            //混合付款必须整单退
            //整单退小票 并且从未被退过-------------------------------------
            if (record.is_return != 1) {
                $scope.check_total_return = true;
                //$scope.check_total_readonly = true;
                $scope.total_return();
            }
        };
        //点击退单查询按钮   0011 4480 0220 1740 -----------------------------------
        $scope.receipt_search = function () {

            reset();
            if ($scope.input_keyword == '') {
                baison_app.api.toast({msg: $rootScope.language.TIPS_CASHIER_INPUT_BILLS_NUMBER})
                return;
            }
            var key = $scope.input_keyword;
            ReceiptRecord.get_one(key).then(function (response) {
                if (response.data.status != 1) {
                    baison_app.api.toast({msg: $rootScope.language[response.data.code]}); //弹出服务器返回的message
                } else {
                    var record = response.data.data.record;
                    //不可退小票 -------------------------------------------------
                    if (record.num < 0) {
                        baison_app.api.toast({msg: $rootScope.language.MSG_CANT_RETURN_THE_DOCUMENTS}); //'该单据为退单不能退货'
                        return;
                    }
                    if (record.is_cancel == 1) {
                        baison_app.api.toast({msg: $rootScope.language.MSG_CANT_RETURN_THE_DOCUMENTS}); //'该单据为退单不能退货'
                        return;
                    }
                    if (record.is_checkout == 0) {
                        baison_app.api.toast({msg: $rootScope.language.MSG_CANT_RETURN_THE_DOCUMENTS}); //'该单据未收款不能退货'
                        return;
                    }
                    if (response.data.data.record.is_add_person == '000') {
                        response.data.data.record.is_add_person = $rootScope.language.TIPS_SUPER_ADMINE; //'超级管理员'
                        $scope.record_info = response.data.data.record;
                        $scope.record_list = response.data.data.record_detail;
                    } else if (response.data.data.record.is_add_person == undefined) {
                        //console.log(response.data.data.record);
                        PosUser.get_user_by_code(response.data.data.record.trade_user_code).then(function (ret) {
                            if (ret.UserName != undefined) {
                                $scope.record_info.is_add_person = ret.UserName;
                            }
                        });
                        $scope.record_list = response.data.data.record_detail;
                        $scope.record_info = response.data.data.record;
                    } else {

                        PosUser.get_user_by_code(response.data.data.record.is_add_person).then(function (ret) {
                            if (ret.UserName != undefined) {
                                $scope.record_info.is_add_person = ret.UserName;
                            }
                        });
                        $scope.record_list = response.data.data.record_detail;
                        $scope.record_info = response.data.data.record;

                    }
                    //console.log(JSON.stringify($scope.record_list));
                    $scope.record_list.forEach(function (e, i) {
                        if ($scope.record_info.cut_money > 0) {
                            $scope.record_list[i].goods_status = 1;
                        }
                        $scope.record_list[i].select_num = 0;
                    });
                    $scope.payment_list = response.data.data.payment;
                    //$scope.promotion = response.data.data.promotion;
                    //baison_app.api.alert({msg:$scope.record_info,title:'recordinfo'});
                    total_return_logic(record);
                    if (is_return) {
                        baison_app.api.toast({msg: $rootScope.language.MSG_REFUND_SUCCESS}); //'退款成功'
                        is_return = 0;
                    }
                }
            });
        };
        //查询更多退单 -----------------------------------------------------------
        $scope.receipt_search_more = function () {
            $location.path('/order/xiaopiao_list/returnable');
        };
        $scope.total_pay_money = 0;
        //计算促销退款价格  一类：共享促销 、单个促销 、vip积分、优惠券   二类：套餐 、不是促销
        var get_return_money = function () {
            var is_pro = false; //是否为一类
            for (var i = 0; i < $scope.return_list.length; i++) {
                if ($scope.return_list[i].goods_status > 0) {
                    is_pro = true;
                    break;
                }
            }

            if ($scope.check_total_readonly && ($scope.payment_list.length > 1 || $scope.record_info.cut_money > 0)) {
                is_pro = true;
            }

            var is_return_num = 0;
            var single_money = 0;
            var un_return_money = 0;
            var total_pay_money = 0;
            if (is_pro) {
                $scope.record_list.forEach(function (e, i) {
                    is_return_num = e.num - e.return_num - e.select_num;
                    if (is_return_num != 0) {
                        single_money = parseFloat(e.money / e.num).toFixed(2);
                        un_return_money = parseFloat(un_return_money) + parseFloat(single_money * is_return_num);
                    }

                });
                $.each($scope.payment_list, function (k, v) {

                    if (v.trade_type_code != '003' && v.trade_type_code != '004') {
                        total_pay_money = parseFloat(total_pay_money) + parseFloat(v.money);
                    }

                });
                //console.log(total_pay_money);
                //console.log($scope.record_info.money);
                $scope.total_pay_money = total_pay_money;
                $scope.return_info.money = total_pay_money - un_return_money;
            }
            //二类不做处理


        };
        //退货数据封装
        var add_to_return_logic = function (goods, pro, num) {
            //退货数据封装
            num = parseInt(num);
            var val = goods.num - goods.return_num - goods.select_num; //可退数量
            if (val > num) {
                val = num;
            }
            var data = {};
            data.user_code = $rootScope.user.UserCode;
            data.goods_code = goods.goods_code;
            data.color_code = goods.color_code;
            data.size_code = goods.size_code;
            data.color_name = goods.color_name;
            data.size_name = goods.size_name;
            data.guide_user_code = goods.guide_user_code;
            data.guide_user_name = goods.guide_user_name;
            data.refer_price = Number(goods.refer_price).toFixed(2);
            data.goods_name = goods.goods_name;
            data.sku = goods.sku;
            data.avg_money = Number(goods.money / goods.num).toFixed(2); //Number(obj.attr('avg_money')).toFixed(2);
            data.detail_index = goods.detail_index; //平板与服务器商品详细关联
            data.num = val;
            data.money = data.avg_money * data.num;
            data.price = goods.price;
            data.goods_status = goods.goods_status;
            data.rebate = goods.rebate;
            if (val <= 0 && pro == 0) {
                baison_app.api.toast({msg: $rootScope.language.MSG_GOODS_BEYOND_LIMIT_OR_NOT_RETURN}); //'本商品已超出退货限额或者不可退！'
                return;
            } else if (val <= 0 && pro == 1) {
                return;
            }
            var return_list = {};
            $scope.record_list.forEach(function (e, i) {
                if (e.detail_index == goods.detail_index) {
                    $scope.record_list[i].select_num = $scope.record_list[i].select_num + val;
                }
            });
            $scope.return_list.push(data);
            $scope.return_info.money = 0;
            $scope.return_info.num = 0;
            $scope.return_list.forEach(function (e, i) {
                $scope.return_info.money += e.money;
                $scope.return_info.num += e.num;
            });
        };
        //添加退货商品到退货列表 --------------------------------------------------
        $scope.add_to_return = function (goods) {
            if ($scope.check_total_readonly && ($scope.payment_list.length > 1 || $scope.record_info.cut_money > 0)) {
                baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_MIXED_PAY_SHALL_REFUND}); //'混合支付须整单退款'
                return;
            }
            if (goods.goods_status && goods.goods_status != 0) { //促销商品
                $.each($scope.record_list, function (k, v) {
                    if (v.goods_status == goods.goods_status && goods.goods_status < 10) {//促销
                        add_to_return_logic(v, 1, v.num);
                    } else if (v.goods_status == goods.goods_status) { //套装
                        add_to_return_logic(v, 1, 1);
                    }
                });
            } else {
                add_to_return_logic(goods, 0, 1);
            }

            //有促销时 计算促销退款价格  一类：共享促销 、单个促销    二类：套餐 、不是促销
            get_return_money();
        };
        //从退货列表中删除一个商品 --------------------------------------------------
        $scope.remove_from_return_list = function (index) {
            //强制整单退的 不可删除单个商品
            if ($scope.check_total_readonly && ($scope.payment_list.length > 1 || $scope.record_info.cut_money > 0)) {
                baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_MIXED_PAY_SHALL_REFUND}); //'混合支付须整单退款'
                return;
            }
            //还原可退数量
            if ($scope.return_list[index].goods_status && $scope.return_list[index].goods_status != 0) {
                var cancel_list = [];
                cancel_list = cancel_list.concat($scope.return_list);
                var goods_status = $scope.return_list[index].goods_status;
                for (var n = 0; n < cancel_list.length; n++) {
                    if (cancel_list[n].goods_status == goods_status) {
                        for (var i = 0; i < $scope.return_list.length; i++) {
                            if ($scope.return_list[i].goods_status == goods_status) {
                                var detail_index = $scope.return_list[i].detail_index;
                                $scope.record_list.forEach(function (e, k) {
                                    if (e.detail_index == detail_index) {
                                        $scope.record_list[k].select_num = $scope.record_list[k].select_num - $scope.return_list[i].num;
                                    }
                                });
                                $scope.return_list.splice(i, 1);
                                break;
                            }
                        }

                    }
                }

            } else {
                $scope.record_list.forEach(function (e, i) {
                    if (e.detail_index == $scope.return_list[index].detail_index) {
                        $scope.record_list[i].select_num = $scope.record_list[i].select_num - $scope.return_list[index].num;
                    }
                });
                $scope.return_list.splice(index, 1);
            }



            //重新计算退款金额
            $scope.return_info.money = 0;
            $scope.return_info.num = 0;
            $scope.return_list.forEach(function (e, i) {
                $scope.return_info.money += e.money;
                $scope.return_info.num += e.num;
            });
        };
        //pc版，从退货列表中删除一个商品
        $scope.remove_check = function (index) {
            $scope.remove_from_return_list(index);
        };

        //弹出退款确认窗口 --------------------------------------------------------
        $scope.show_return_confirm = function () {
            

            if ($scope.return_list.length == 0) {
                baison_app.api.toast({msg: $rootScope.language.MSG_YOU_HAVINT_ANY_NEED_RETURN_GOODS}); //'您没有选择任何需要退的商品!'
                return;
            }

            //获取退货原因
            BaseGoods.returnReason().then(function (ret) {
                if (ret[0] != undefined) {
                    $scope.trade_type_name = ret[0].trade_type_code;
                    $scope.return_reason = ret;
                }

            });
            returnXP = confirm_window = ngDialog.open({closeByDocument: false,
                trapFocus: false,
                template: './html/cashier/return_confirm.html',
                disableAnimation: true,
                scope: $scope

            });
        };
        //判断是否可以退款（飞凡支付没有开启情况下不予退款）
        var check_is_return = function(){
            var is_check = false;
            var is_ok = false;
            $.each($scope.payment_list,function(i,v){
                if(v.trade_type_code == "103"){
                    is_check = true;
                }
            });
            if(is_check){
                var systype = baison_app.api.systemType;
                if(systype != 'android'){
                    baison_app.api.toast({msg: $rootScope.language.TIPS_FEIFAN_OPERATE+$rootScope.language.MSG_FEIFAN_MODULE_NOT_SYS}); //"MSG_FEIFAN_MODULE_NOT_SYS":"只能在android系统上使用",
                    ok = false;
                    
                }
                var configData = $api.getStorage('configData');
                if (!configData.feifan.switch) {
                    baison_app.api.toast({msg: $rootScope.language.MSG_FEIFAN_MODULE_NOT_OPEN}); //模块未开启
                    ok = false;
                }
                if (!baison_app.feifanPay) {
                    baison_app.api.toast({msg: $rootScope.language.MSG_FEIFAN_MODULE_NOT_INSTALL}); //'模块未安装'
                    ok = false;
                }
            }else{
                ok = true;
            }
            if(!ok){
                $scope.receipt_search();
            }
            return ok;
            
        };
        //更新库存
        //获取discutmoney 
        var get_return_discount_money = function () {
            var total_money = $scope.record_info.money;
            var pay_money = $scope.total_pay_money;
            return (pay_money <= 0) ? 0.00 : 0 - (parseFloat(total_money - pay_money));
        };
        //确认退单 --------------------------------------------------------------
        $scope.return_confirm = function (trade_type_name) {   
            var key = $scope.input_keyword;
            //added by maowei on 20170216 确认退单并打印 start 
            //获取小票商品明细信息
            var get_goods_detail_infos = function(record_detail){
                var deferred = $q.defer();
                var promise = deferred.promise;
                record_detail.forEach(function(n,i){
                    deferred[i] = $q.defer();
                    promise[i] = deferred[i].promise;
                    dbGetOne('select weight,unit_name from PosGoods where GoodsCode="' + n.goods_code + '"').then(function(ret){
                        n.weight = ret.weight;
                        n.unit_name = ret.unit_name;
                        deferred[i].resolve('success');
                    });
                   
                });
                return $q.all(promise);
            };
            
            //获取小票信息
            ReceiptRecord.get_one(key).then(function (ret) {
                var record = {};
                var configData = $api.getStorage('configData');
                var printNum = parseInt(configData.printData['num'], 10);
                var printData = configData.printData;
                var shop_addr = '';
                var shop_tel = '';
                var web_site = '';
                var shop_name = '';
                if (printData != undefined) {
                    shop_addr = printData['addr'];
                    shop_tel = printData['tel'];
                    web_site = printData['web_site'];
                }
                ShopSearch(ret.data.data.record.shop_code).then(function (n) {

                    shop_name = n[0].ShopName;
                    record.record_code = ret.data.data.record.record_code;
                    record.record_time = ret.data.data.record.record_time;
                    record.vip_code = ret.data.data.record.vip_code;
                    record.pay_money = ret.data.data.record.final_money;
                    record.total_num = ret.data.data.record.num;
                    record.total_money = ret.data.data.record.money;
                    record.shop_name = shop_name;
                    record.user_code = ret.data.data.record.trade_user_code; //收银员
                    record.user_name = ret.data.data.record.trade_user_name; 
                    record.guide_user_name = commonInterface.get_guides_user_name(ret.data.data.record_detail);//导购员
                    record.brand_name = $rootScope.language.TIP_ORDER_RECEIPT_BRAND_NAME;
                    record.shop_addr = shop_addr;
                    record.shop_tel = shop_tel;
                    record.web_site = web_site;
                    record.record_detail = ret.data.data.record_detail;
                    record.payment = ret.data.data.payment;
                    get_goods_detail_infos(record.record_detail).then(function(){
                        /*
                        Print.xp_print($rootScope.language.TUI_DAN_XP, record);
                        */
                        if(isNaN(printNum) || printNum < 1){
                            printNum = 1;
                        }
                        var execute_print = function(print_index){
                            if(print_index >= printNum){
                                return;
                            }
                            Print.xp_print($rootScope.language.TUI_DAN_XP, record);
                            print_index++;
                            //alert(print_index);
                            execute_print(print_index);
                        };
                        execute_print(0);
                        
                    });
                    
                });
            });
            //added by maowei on 20170216 end
          
            var reason = '';
            $.each($scope.return_reason, function (i, v) {
                if (v.trade_type_code == trade_type_name) {
                    reason = v.trade_type_name;
                }
            });
            ngDialog.close(confirm_window);
            //获取discutmoney 
            var discount_money = get_return_discount_money();
            //TODO 生成退货订单  返回收银主界面
            var return_data = {
                init_code: $scope.record_info.record_code,
                discount_money: discount_money,
                remark: '',
                payment_list: $scope.payment_list,
                vip: {
                    vip_code: $scope.record_info.vip_code,
                    customer_code: $scope.record_info.customer_code
                },
                info: {
                    total_num: $scope.return_info.num,
                    total_money: parseFloat($scope.return_info.money - discount_money),
                    pay_money: $scope.return_info.money
                },
                list: $scope.return_list,
                reason: reason
            };

            //console.log(return_data);
            if(check_is_return()){
                ReceiptRecord.add_return(return_data).then(function (ret) {
                    if(ret.status == 0){
                        $location.path("/order/xiaopiao_list/"+"main");
                        return;
                    }
                    if(ret.data != undefined && ret.data.status == -1){
                        baison_app.api.toast({msg: ret.data.message}); //'模块未安装'
                        return;
                    }else{
                        //更新库存
                        ReceiptRecord.update_skunum(return_data.list, 1);
                        $scope.input_keyword = $scope.record_info.record_code;
                        is_return = 1;
                    }
                    
                    $scope.receipt_search();
                });
            }
            
            $scope.return_list = [];
            ngDialog.close(returnXP);
//        $scope.show_return_confirm();
        };
        //初始时是否根据传递参数进行查询 -------------------------------------------
        if ($routeParams.record_code != 'null') {
            $scope.input_keyword = $routeParams.record_code;
            $scope.receipt_search();
        }
    }];
CashierIndexCtrl.$injector = ['$scope', '$rootScope', '$location', '$interval', '$timeout', 'ShopGetFriend', 'BaseGoods', 'GoodsCart', 'VIP', 'Coupon', 'UserLoginCheck', 'ReceiptRecord', 'ngDialog', 'ShopSetCheck', 'Promotion', 'timeStamp2String', 'Cards', 'PosUser', 'LackRegister', 'ServiceOrder', 'ShopAttend', 'apiService', 'ThirdDev'];
CashierSettleCtrl.$injector = ['$q', '$scope', '$rootScope', '$location', 'GoodsCart', 'checkGetList', 'ReceiptRecord', 'ngDialog', 'WeiXin_ZF', 'ZhiFuBao_ZF', 'timeStamp2String', 'Print', 'SysConfig', 'tuiKu', 'Coupon', 'Cards', 'shortCutAction', 'commonInterface', 'ServiceOrder','dbGetOne'];
CashierReturnCtrl.$injector = ['$scope', '$rootScope', '$routeParams', '$location', 'ReceiptRecord', 'ngDialog', 'apiService', 'ShopSetCheck', 'checkGetList', 'WeiXin_ZF', 'ZhiFuBao_ZF', 'BaseGoods', 'PosUser'];